Please explain me why it behaves differently.
int main() {
int p;
p = (printf("stack"),printf("overflow"));
printf("%d",p);
return 0;
}
This gives the output as stackoverflow8. However , if I remove the paranthesis , then :
p = printf("stack"),printf("overflow");
gives the output as stackoverflow5
The Comma Operator
The comma operator has lower precedence than assignment (it has a lower precedence than any operator for that matter), so if you remove the parentheses the assignment takes place first and the result of the second expression is discarded. So...
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 cause an error as it is interpreted as a re-declaration of b
, i.e.:
int y = a;
int b;
I missed this at first, but it makes sense. It is no different than the initial declaration of a
and b
, and in this case the comma is not an operator, it is a separator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With