C++ Comma Confusion

Quick: evalute the following C++ code:
i = g(), h();
i = ( g(), h() );
i = f( g(), h() );
I observed an interesting discussion about commas not too long ago. The comma operator is a strange beast, and not often seen in typical C++ code. Most typically, you see it in loops, such as: for( i = 0, j = j; i < MAX; i++, j++ ).
The confusing thing about commas in C++ is that they can have multiple meanings. Let’s dissect the code above. The first line works as follows:
  1. Execute function g().
  2. Put the results of g() into i. (The equals operator has a higher precedence than the comma operator).
  3. Execute the function h().
The second line works thus:
  1. Execute function g().
  2. Execute function h(). h() is always guaranteed to be executed after g() is complete, because the comma operator requires left-to-right evaluation.
  3. Put the results of h() into i. The rightmost value of the comma operator (in this case, the function h()) is the resulting value of the comma operator.
The third line doesn’t have a comma operator. The commas in a function parameter list simply separate parameters. The third line works as follows:
g() and h() may be executed in any order. That’s right. The order of evaluation is unspecified. This allows compilers to perform interesting optimizations. Once both g() and h() have completed, the results are passed to function f().
Many C++ programmers are surprised by the effects of that little comma. In some cases (e.g. comma operator), the comma very clearly describes the order of operations. In other cases (e.g. function parameter separators), the comma does not describe the order. h() could execute before g() in the last example, and it often does in real compilers. Understanding the difference is well worth your time.
This entry was posted in C++. Bookmark the permalink.

One Response to C++ Comma Confusion

  1. Unknown says:

    i don’t know why this confusing operator is exist in C++ syntax. in actually, the first line can be replaced with [i=g(); h();] and the 2st line with [g(); i=h();]. you’d better not using comma operator in your code (except in loop).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s