0

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;
}
4
Contributors
4
Replies
32
Views
5 Years
Discussion Span
Last Post by MRehanQadri
2

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

Votes + Comments
Thanks a lot, I was almost gone mad for my mistake.
0

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

3

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'))
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.