Why the condition if ((a[0] == 'y') | (a[0] = 'Y')) is ALWAYS TRUE in the following code?

#include <iostream>
using namespace std;

int main()
{
    cout << "Enter 10 integers seperated by spaces: ";
    int array[10];
    for (int i = 0; i<1; i++)
        cin>>array[i];
    cin.ignore();
    cout << "Do you like to search an element in the array? ";
    char a[4];
    cin.getline(a,4,'\n');

    if ((a[0] == 'y') | (a[0] = 'Y'))
    {
        cout << "TRUE";
    }
    else
        cout << "FALSE";
    cout << endl;
}
Re: Why Condition is always true? 80 80

Because the second halv of that statement is the assignment operator = instead of boolean operator ==.

commented: Thanks a lot, I was almost gone mad for my mistake. +0
Re: Why Condition is always true? 80 80

Most common error made in if statements: using "=" instead of "==", lots of fun to figure out the logic error tho isn't it?

Re: Why Condition is always true? 80 80

The logical OR (||) and bitwise OR (|) are also subtly different. Sometimes you'll get the same result and sometimes you'll be surprised, so I'd recommend not using the bitwise OR in situations where you clearly want a logical OR. This is one of those situations, so your test should be:

if ((a[0] == 'y') || (a[0] == 'Y'))
Re: Why Condition is always true? 80 80

Thanks to every one.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.