or operator if statement

Jun 25, 2013 at 12:40pm
Why is this all the times true?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>

using namespace std;

int main()
{
    char answer;
    int pause;

cin >> answer;
    
if (answer == 'y' || 'Y')
 cout << "Why\n";

else
 cout << "No\n";
    
    cin >> pause;
}


Jun 25, 2013 at 12:47pm
In line 12, the two statements being evaluated for the "or" are:

1
2
answer == 'y'
'Y'

Since 'Y' is non-zero, the "or" condition will always be true.

You need to do some more reading about how to construct logical conditions in C++.
Jun 25, 2013 at 12:49pm
|| takes two arguments, in your case answer == 'y' and 'Y', and returns false if both arguments are false otherwise it returns true. If an integer is used in place of a boolean 0 will be treated as false and everything else as true. 'Y' is not 0 so it will treated as true, so that is why the whole or-expression returns true.
Jun 25, 2013 at 12:53pm
try...

if(answer == 'y' || answer == 'Y')
Jun 25, 2013 at 12:58pm
Thank you Manga. Been long time since I used C++ and just been seeing what I remember.
Topic archived. No new replies allowed.