Why is the output different?

Please explain to me why this behaves differently.

int main() { int p; p = (printf("stack"),printf("overflow")); printf("%d",p); return 0; } 

This gives the result as stackoverflow8. However, if I remove the parenthesis, then:

p = printf("stack"),printf("overflow"); gives the result as stackoverflow5

+6
source share
1 answer

Comma Operator

The comma operator has a lower priority than assignment (it has a lower priority than any operator in this regard), so if you remove the brackets, the assignment is executed first, and the result of the second expression is discarded. So that...

 int a = 10, b = 20; int x = (a,b); // x == 20 int y = a,b; // y == 10 // equivalent (in terms of assignment) to //int y = a; 

Note that the third line will throw an error because it is interpreted as a repeated declaration of b , i.e.:

 int y = a; int b; 

At first I skipped this, but it makes sense. This is no different from the initial declaration of a and b , in which case the comma is not an operator, it is a separator.

+13
source

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


All Articles