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.
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.
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.