int main()
{
int x=7,z;
int y=8;
z=x,y;
printf("%d",z);
}
Why are we getting 7 as result
The comma operator , evaluates its left operand, discards the value, and uses the right operand as the result of the operator. However it also has the lowest precedence, lower even than the assignment operator =. So this:
z=x,y;
Parses as:
(z=x),y;
So in this expression, z gets assigned the value of x which is 7. That value, being the left operand of the comma operator, gets discarded and the value of y is evaluated. The final value of the expression, 8, then gets discarded as well as it is the final value of an expression statement.
Had you done this:
z=(x,y);
Then the comma operator would evaluate to the value of y which is 8, then that value would get assigned to z.
int x, z; declares both x and z as integer variables. By adding the x=7 you're simply initializing it. In a similar vein, z=x sets z to the value of x. The y in that statement does nothing.
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