Here's what I understand so far:
The comma operator allows for brevity of code, e.g. int x = 0, y = 0, z = 0
as opposed to int x = 0; int y = 0; int z = 0;
. In this case it's sort of like syntactic sugar for a semicolon.
The comma operator acts as a sequence point. So in the code f(), g();
, the function f()
is guaranteed to execute and produce all of its side effects before g()
. But the same is true if you use the code f(); g();
.
The comma operator is an operator, whereas the semicolon is simply a program token that takes no part in the evaluation of expressions. Since the comma operator has such low precedence, it differs very little from the semicolon in this regard.
So, I'm wondering what is the semantic difference between these two constructs in practice? Is there any situation where using a comma would produce different results from using a semicolon?
There are cases where comma is used as a token, there are other cases where the comma is a comma operator.
Quoting wikipedia,
The use of the comma token as an operator is distinct from its use in function calls and definitions, variable declarations, enum declarations, and similar constructs, where it acts as a separator.
One example to clarify, (borrowed directly from chapter §6.5.17, C11
standard)
You can have a function call made like
f(a, (t=3, t+2), c);
here, the comma in (t=3, t+2)
is a comma operator, this is valid and accepted.
However, you cannot write
f(a, (t=3; t+2), c);
this is a syntactic error.