How does the Comma Operator work

Take care to notice that the comma operator may be overloaded in C++. The actual behaviour may thus be very different from the one expected.

As an example, Boost.Spirit uses the comma operator quite cleverly to implement list initializers for symbol tables. Thus, it makes the following syntax possible and meaningful:

keywords = "and", "or", "not", "xor";

Notice that due to operator precedence, the code is (intentionally!) identical to

(((keywords = "and"), "or"), "not"), "xor";

That is, the first operator called is keywords.operator =("and") which returns a proxy object on which the remaining operator,s are invoked:

keywords.operator =("and").operator ,("or").operator ,("not").operator ,("xor");

The comma operator has the lowest precedence of all C/C++ operators. Therefore it's always the last one to bind to an expression, meaning this:

a = b, c;

is equivalent to:

(a = b), c;

Another interesting fact is that the comma operator introduces a sequence point. This means that the expression:

a+b, c(), d

is guaranteed to have its three subexpressions (a+b, c() and d) evaluated in order. This is significant if they have side-effects. Normally compilers are allowed to evaluate subexpressions in whatever order they find fit; for example, in a function call:

someFunc(arg1, arg2, arg3)

arguments can be evaluated in an arbitrary order. Note that the commas in the function call are not operators; they are separators.