2

I was reading this question about sequence points and I saw this line:

i = (i, ++i, 1) + 1; // well defined (AFAIK)

I was wondering how is the following syntax called and what are its effects?

i = (a1, a2, ...,an);

Guillaume D
  • 2,202
  • 2
  • 10
  • 37
  • It evaluates each term sequentially and assigns the last term evaluated to `i`. – Paul Ogilvie Jun 20 '19 at 12:39
  • 1
    It’s the comma operator. It’s the lowest priority operator. There is a sequence point between evaluating the left and right sides of the operator. – Jonathan Leffler Jun 20 '19 at 12:39
  • 1
    Not every expression that is well defined should be written. This one is useless. – Slava Jun 20 '19 at 12:42
  • 1
    Unrelated, I think it is still UB. Because the left `i = ` is unsequenced in relation to the `(i,`, regardless of the commas. You'd have to write something like `i = (0, i, ++i,0);` – Lundin Jun 20 '19 at 12:46
  • I believe the validity of this depends on whether you're programming in C or new-ish C++ or old-ish C++. – molbdnilo Jun 20 '19 at 13:09

1 Answers1

3

This is the comma operator for int operands, together with grouping through parentheses, which is always allowed. First,

(i, ++i, 1)

evaluates i, then ++i, then 1 and returns the result of the last expression (which is 1). Then

(i, ++i, 1) + 1

is the same as

1 + 1;

which results in 2, so i is set to 2 here. Note that without the parentheses, the result would in most cases not be the same, as the comma operator has the lowest possible precedence (thanks to @dbush for helping me out here in the comments).

lubgr
  • 37,368
  • 3
  • 66
  • 117
  • 1
    The result without parenthesis is *not* the same. In that case the statement parses as `(i = i), ++i, (1 + 1);`, which results in the prior value of `i` getting incremented. – dbush Jun 20 '19 at 12:44
  • @dbush You're right, thanks I was thinking through this code with a contrived initial value of `i` as `1`, but that's bogus... – lubgr Jun 20 '19 at 12:45