0

If I write code using comma operator like this:

int i;
i = 5, i++, i++;

does it invoke undefined behavior?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Jayesh
  • 4,755
  • 9
  • 32
  • 62

3 Answers3

5

No. It will not invoke undefined behavior as there is a sequence point between evaluation of left and right operands of comma operators.

= has higher precedence than that of , operator and therefore 5 will bind to = as

(i = 5), i++, i++;

Since operands of comma operator guaranteed to evaluates from left to right, i = 5 will be evaluated first and i will be assigned 5, then the second expression i++ will be evaluated and i will be 6 and finally the third expression will increment i to 7.

The above statement is equivalent to

i = 5;
i++;
i++;
haccks
  • 104,019
  • 25
  • 176
  • 264
5

does it invoke undefined behavior?

No, because of both the sequence points the comma operator introduces and operator precedence. A sequence point assures that all side effects of the previous evaluations have been performed before evaluating the following expressions.

Sequence points and operator precende assure that in the i = 5, i++, i++; statement, i will be initialized before evaluating any of the i++ expressions.

The statement:

i = 5, i++, i++;

is, considering operator precedence, equivalent to:

((i = 5), i++), i++;

So, first (i = 5) is evaluated. After its side effects are over (i.e.: after i is initialized to 5), the following expression, i++ is evaluated. Again, after the side effect this last expression introduces is over (i.e.: i is increased by one), the last expression, i++, is evaluated.

JFMR
  • 23,265
  • 4
  • 52
  • 76
  • 1
    You might want to stress that it's the combination of operator precedence and sequencing that make it not UB. The sequencing in itself is not enough. – Some programmer dude Sep 14 '17 at 06:36
  • @Someprogrammerdude you mean is the assignment what prevents this statement from being UB? – JFMR Sep 14 '17 at 06:42
  • 1
    Yes, that's what someprogrammerdude is saying. `i = (5, i++, i++)` would have undefined behaviour. – Peter Sep 14 '17 at 06:43
  • What you have is correct as far as it goes, but does not mention the reliance on operator precedence, which was someprogrammerdude's key point. Operator precedence (or, more accurately, the language rules that result in what we describe as operator precedence) are the reason `i = 5, i++, i++` is equivalent to `(i = 5), i++, i++` not to `i = (5, i++, i++)` which has undefined behaviour. – Peter Sep 14 '17 at 07:00
  • @Peter Thanks a lot. – JFMR Sep 14 '17 at 07:22
1

No, does not invoke undefined behavior because the comma operator is a sequence point. i is assigned a value of 5 and then incremented twice.

msc
  • 33,420
  • 29
  • 119
  • 214