In C and C++, is an expression using the comma operator like `a = b, ++a;` undefined?

  • A+

Take these three snippets of C code:

1) a = b + a++ 2) a = b + a; a++ 3) a = b + a, a++ 

Every Russian schoolboy knows that example 1 is a Very Bad Thing, and clearly invokes undefined behavior. Example 2 has no problems. My question is regarding example 3. Does the comma operator work like a semicolon in this kind of expression? Are 2 and 3 equivalent or is 3 just as undefined as 1?

Specifically I was considering this regarding something like free(foo), foo = bar. This is basically the same problem as above. Can I be sure that foo is freed before it's reassigned, or is this a clear sequence point problem?

I am aware that both examples are largely pointless and it makes far more sense to just use a semicolon and be done with it. I'm just asking out of curiosity.

Case 3 is well defined.

Section 6.5.17 of the C standard regarding the comma operator , says the following:

2 The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value

Section 5.14 p1 of the C++11 standard has similar language:

A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded- value expression. Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression. The type and value of the result are the type and value of the right operand; the result is of the same value category as its right operand, and is a bit-field if its right operand is a glvalue and a bit-field.

Because of the sequence point, a = b + a is guaranteed to be fully evaluated before a++ in the expression a = b + a, a++.

Regarding free(foo), foo = bar, this also guarantees that foo is free'ed before a new value is assigned.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: