Why does this code not output anything?

Consider this "EXAM" question:

int main() { int a=10,b=20; char x=1,y=0; if(a,b,x,y) { printf("EXAM"); } } 

Please let me know why this doesn't print anything.

+4
source share
5 answers

Comma operator - evaluates the first expression and returns the second. So a,b,x,y will return the value stored in y, i.e. 0.

+11
source

The result of a,b,x,y is equal to y (because the comma operator evaluates the result of its right operand), and y is 0, which is incorrect.

+3
source

The comma operator returns the last operator, which is equal to y . Since y is zero, the if statement evaluates to false, so printf never executed.

+2
source

Since the expression a,b,x,y evaluates to y , which in turn evaluates to 0 , so the corresponding block is never executed. The Comma statement executes each statement and returns the value of the latter. If you need a logical conjunction, use the && operator:

 if (a && b && x && y) { ... } 
+1
source

Others have already mentioned that the comma operator returns the rightmost value. If you want to print the value, if ANY of these variables are true, use boolean or:

 int main() { int a=10,b=20; char x=1,y=0; if(a || b || x || y) { printf("EXAM"); } } 

But then keep in mind that the comma evaluates all expressions, while the statement or stops as soon as the value is true. So,

 int a = 1; int b; if(a || b = 1) { ... } 

b is undefined, whereas

 int a = 1; int b; if(a, b = 1) { ... } 

b will be set to 1.

0
source

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


All Articles