Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using comma operator in c

I have read that comma operator is used to assign expression, and the right expression is supplied to lvalue.

But why does this program assign left expression to lvalue when not using parenthesis? I am using turbo c compiler.

int b=2;
int a;
a=(b+2,b*5);  // prints 10 as expected
a=b+2,b*5;    // prints 4 when not using parenthesis

Also the following works:

int a =(b+2,b*5);

But this generates an error:

int a =b+2,b*5;   // Error

I can't understand why.

like image 414
Sanjana Avatar asked Feb 16 '23 08:02

Sanjana


1 Answers

Because precedence of , operator is lower than of = one, this...

a=b+2,b*5;

... will actually be evaluated as...

a = b + 2;
b * 5;

With int i = b + 2, b * 5; is a bit different, because comma has different meaning in declaration statements, separating different declarations from each other. Consider this:

int a = 3, b = 4;

You still have comma here, but now it separates two variable assignment-on-declarations. And that's how the compiler attempts to treat that line from your example - but fails to get any meaning from b * 5 line (it's neither assignment nor declaration).

Now, int a = (b + 2, b * 5) is different: you assign a value of b + 2, b * 5 expression to a variable a of type int. The first sub-expression is discarded, leaving you just with b * 5.

like image 141
raina77ow Avatar answered Feb 24 '23 01:02

raina77ow