Search code examples
cundefined-behaviorcomma-operator

Is writing 3 instructions separated by comma `,` undefined behaviour?


I think that I saw somewhere that writing more than 1 instruction separated by a comma , is undefined behavior.

So does the following code generate undefined behavior?

for (i=0, j=3, k=1; i<3 && j<9 && k<5; i++, j++, k++) {
    printf("%d %d %d\n", i, j, k);
}

because there are 3 instructions separated by a comma , :

i++, j++, k++

Solution

  • writing more than 1 instruction separated by comma , is undefined behaviour.

    Nope, it's not the general case.

    In your case, i++, j++, k++ is perfectly valid.

    FWIW, as per C11, chapter §6.5.17, Comma operator (emphasis mine)

    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; [...]


    [Note]: You might have got confused by seeing something along the line of

      printf("%d %d %d", i++, ++i, i);
    

    kind of statement, but do note, there the , is not a comma operator altogether (rather, a separator for supplied arguments) and the sequencing does not happen. So, those kind of statements are UB.

    Again, referring to the standard, footnote 3 for the same chapter

    As indicated by the syntax, the comma operator (as described in this subclause) cannot appear in contexts where a comma is used to separate items in a list (such as arguments to functions or lists of initializers).