Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this assigning of variables work?

Tags:

c

int main()
{
    int x=7,z;
    int y=8;

    z=x,y;
    printf("%d",z);
}

Why are we getting 7 as result

like image 969
Rashi Avatar asked Oct 21 '25 09:10

Rashi


2 Answers

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.

like image 142
dbush Avatar answered Oct 23 '25 21:10

dbush


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.

like image 41
scatter Avatar answered Oct 23 '25 23:10

scatter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!