Equality with OR operator precedence

I was checking the first letter of the response with the letters ‘y’ and ‘Y’ and had this doubt.
When i type this way I always end up getting up false even if the input entered is “yes”.

if (Response[0] == ('y' || 'Y'))
	cout << "true";
	cout << "false";

But when I frame it this way I get the correct output. Can someone please explain what is going on here. Thanks.

if (Response[0] == 'y' || Response[0] == 'Y')
	cout << "true";
	cout << "false";

Because you need a full statement for a comparison. ‘y’ and ‘Y’ will just be implicitly converted to a boolean value (all non-zero values are true). So you effectively have Response[0] == (true || true)

1 Like

As @DanM was stating you always need to rewrite the full statement.

The first one is asking “Is the result y or Y” and the second one is asking “Is the result y or is the result Y”. Now that sounds pretty stupid in English because we’ll mostly read it as the exact same, but to be extreamly technical (key word) only the second one ask if Y is the result, the first just says “Y?”.

A rule of thumb for this is that you always need to be able to make as many full sentences out of it as their are options given. You can make 2 full senteces out of “Is the result y or is the result Y” while you only the “Is the result y” and “Y” out of the first one. I hope that clears it up a bit.

I think you missed the () as you seem to be talking as if the statement is Response[0] == 'y' || 'Y'

Yup. Continuing from there, it evaluates to

Response[0] == true

which is done as

Response[0] == 1

which will be false because 1 is not the code for any alphabetic character. The code it is a value for is rather difficult to enter from the keyboard by mistake. (On a PC, Ctrl-A should do it, but getline might not pass it in :wink:.

Privacy & Terms