Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are "arithmetic expressions" separated by commas allowed in C or we need separate statements for each?

In C, is the following statement

a+=3,b=c*2,d=a+b;

equivalent to the following block of statements:

a+=3;
b=c*2;
d=a+b;

I am sure you got my point. Can we safely use multiple mathematical expressions separated by commas in the same statement in C? And in what cases this can pose problems?

like image 351
T Singh Avatar asked Oct 29 '25 09:10

T Singh


1 Answers

It might be easier if you think of the comma-expression list you present like this:

((a += 3, b = c * 2), d = a + b)

First the innermost comma-expression is evaluated:

a += 3, b = c * 2

That expression will be evaluated in two steps:

a += 3
b = c * 2

The result of a += 3 will be thrown away by the compiler, but the assignment still happens, it's just that the returned result is thrown away. The result of the first comma expression is b (which will be c * 2 (whatever that is)).

The result of the first comma expression is then on the left-hand side of the next comma expression:

b = c * 2, d = a + b

Which will then be sequenced as

b = c * 2
d = a + b

The result of the expression b = c * 2 is thrown away (but as it is still evaluated the assignment still happens), and the result of the complete expression is d (which is a + b).

The result of the whole expression will be d.

like image 99
Some programmer dude Avatar answered Nov 01 '25 09:11

Some programmer dude