Does || not work in if statements?

Does something like this not work or was there just something else wrong with my code? I had a whole bunch of if statements with || in it and ended up changing all of them expect one because I was sure it was the code, but the one I was 100% would work had a problem and when I took out the || it fixed it.

1
2
3
4
5
6
7
8
9
10
11
char choice;

cout << "Do you want a cookie?" << endl;
cin >> choice;

if(choice == 'Y' || 'y'){ // Y for Yes
cout << "Here you go" << end;
}

// This isn't the code i'm working on just in case anyone thought it was, this is just an example.
Last edited on
Simply compile your code and see what will the compiler say.:) At least I do not understand what is in the parentrheses.
What that statement means is:

if variable choice. 'Y' or 'y'. It doesn't make any sense.

if (choice == 'Y' || choice == 'y')

That would translate to:

if variable choice is equal to 'Y' or variable choice is equal to 'y'.

Edit: I'm assuming that is what you actually mean.
Last edited on
That's the thing though, I don't get an error that's why I thought it was fine, but it seems like It was causing problems when I run the code. That's why I'm not to sure, if it's just my code or it doesn't work.
There are two problems with your code.
1) the ; is bogus in the if statement.
2) You can't string comparisons together like it appears that you're trying to do.
 
if (choice == 'Y' || 'y')

The above statement will compile, but will not do what you expect.
It will always evaluate to true.
Why? Because of the order of operations.
choice will be compared to 'Y' first. That results in a bool expression (let's assume false). That bool expression will then be or'ed with 'y' (false || 'y'). Since 'y' is non-zero, that expression will always be true.

Yeah that choice; was an accident, but anyway at least I know now it doesn't work. Although I don't completely understand why.
Expression

choice == 'Y' || 'y'

is equivalent to

( choice == 'Y' ) || ( 'y' )

as 'y' has the internal code representation (for example ASCII-code or EBCDIC-code) that is not equal to zero then expression ( 'y' ) will be always evaluated to true. So the whole expression

( choice == 'Y' ) || ( 'y' )

will be always equal to true irrespective of whether choice is equal to 'Y' or not because the right operand of the operator || is always true.
Last edited on
I understand it a little better now, thanks.
Topic archived. No new replies allowed.