Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF statement with logical OR [duplicate]

if(1 == 2 || 4)
{
cout<<"True";
}
else
{
cout<<"False";
}

This is how I read the above. If 1 is equal to 2 or 4, then print true. Otherwise, print false. When this is executed though... true is printed. Obviously I'm misunderstanding something here. 1 is not equal to 2 or 4. Wouldn't that make it false?

like image 209
Mike York Avatar asked Jan 29 '26 14:01

Mike York


1 Answers

Yeah, I've made the same mistake.

Read the sentence again:

If 1 is equal to 2 or 4, then print true.

The "2" and "4" both refer to the "If 1 is equal to [...]." That means, the sentence is just an abbreviation of

If 1 is equal to 2 or 1 is equal to 4, then print true.

This leads us to the if-clause

if (1 == 2 || 1 == 4)

instead.


1 == 2 || 4 is true because (1 == 2) == false ORed with 4 == true, yields true (false OR true = true).

like image 118
cadaniluk Avatar answered Jan 31 '26 03:01

cadaniluk