Does comma separators in type definition in C guarantee the order?

420 views Asked by At

Comma operators have the lowest precedence and left-to-right associativity, so this guarantees the order like:

i = ++j, j = i++;

i will be 2, and then j will be 1 after this statement if i and j are both 0 at first.

However, does comma separators in type definition in C also guarantee the order? Such as

int i = 1, j = ++i;
3

There are 3 answers

4
M.M On BEST ANSWER

Your example with the comma operator, i = ++j, j = i++;, is well-defined because the comma operator is a sequence point.

Precedence/associativity is not enough to guarantee this -- they are different to order-of-evaluation and sequence points. For example, i * 2 + i++ * 3 is undefined because there are no sequence points.


The comma separator between declarators, e.g. int i = 1, j = i++;, is also a sequence point. This is covered by C11 6.7.6/3, C99 6.7.5/3:

A full declarator is a declarator that is not part of another declarator. The end of a full declarator is a sequence point.

So there is a sequence point after i = 1, and this code is well-defined.


However, the comma separator between function arguments f(i, i++) is not a sequence point; so that code causes undefined behaviour.


Note: In C11, the term sequence point was mostly replaced with more complicated sequencing relations in order to clearly specify a threading model, but that does not affect the above discussion.

9
CalebB On

Assuming C works the same as C# in this respect, the comma-separated values (int i = 0, j = 0;) should stay in order.

The difference in i++ vs ++i is validation time:

int i = 0;

bool iGTZ = i++ > 0;//false

i = 0; iGTZ = ++i > 0;//true

A little more than what you asked but the declaration order is guaranteed. And if you or someone reading this didn't know that hopefully it helps. :)

4
Trevor Hart On

Yes, and here's the reason. Think about what the comma is saying. All it is saying is "hey, I have a thing I want to do on the left hand side of this comma, once you do that thing go to the thing on the right and do that as well. You can also think of it as a shorter way of doing this

int i = 1;
int j = i++;

i has already been allocated somewhere in memory so all that happens with j is it takes that value stored in i, increments it, and sets it equal to j.

So in the case of

int i = 1, j = ++i;

All you are saying is create an integer, set it equal to one, now move on to the next command, which will be an int called j, and set it equal to whatever i is when it is incremented.

So to fully answer your question, yes, it guarantee's the order because the compiler will execute everything top down, left to right unless it is told otherwise.