Using a comma operator in c

I read that the comma operator is used to assign an expression, and the correct expression is an lvalue.

But why does this program assign a left lvalue expression when not using parenthesis. I use the 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 

The following work is also performed

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

And this gives rise to an error, I could not understand the reason.

 int a =b+2,b*5; // Error 
+4
source share
1 answer

Since operator priority , lower than = one, this one ...

a=b+2,b*5;

... will actually be rated as ...

 a = b + 2; b * 5; 

C int i = b + 2, b * 5; slightly different because the comma has different meanings in the declaration statements, separating the different declarations from each other. Consider this:

 int a = 3, b = 4; 

You still have a comma, but now it separates the two assignment variables when declaring. And the way the compiler tries to process this line from your example, but does not get any value from line b * 5 (this is not the purpose and declaration).

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

+8
source

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


All Articles