C Confusion of program output

Can someone explain why the output of this program is incorrect?

x && y gives 1. Still the output is false.

#include <stdio.h> int main() { int x = 1, y = 2; if(x && y == 1) { printf("true."); } else { printf("false."); } return 0; } 
+6
source share
4 answers

Because == has a higher priority than && So, this is first evaluated:

 x && (y == 1) 

 y == 1 // 2 == 1 //Result: false 

What is false and then second:

 x && false //1 && false //Result: false 

So the if statement will be false

For more information on operator priority, see here: http://en.cppreference.com/w/cpp/language/operator_precedence

+6
source
 if(x && y == 1) 

Same as

 if( ( x != 0 ) && ( y == 1 ) ) 

Here x != 0 true, but y == 1 is false. And since at least one of the && operands is false, the condition evaluates to false, and else is executed.

+1
source

He clearly identified X = 1 and Y = 2; Now with expression

 X && Y == 1 

The expression evaluates to Y == 1 (Priority rule, False is also output)

X! = 0 (True)

Now && is a logical and operator, so it evaluates to True only if both parts of the expression express True !!!

0
source

This is normal for false, then 2 and 2 and is different from one. What you are asking is that both x and y are worth 1. If that happens, say true but false

0
source

Source: https://habr.com/ru/post/982952/


All Articles