|
The comma operator
The comma is not restricted to separating
variable names in multiple definitions, such as
int i, j, k;
Of course, it’s also used in
function argument lists. However, it can also be used as an operator to separate
expressions – in this case it produces only the value of the last
expression. All the rest of the expressions in the comma-separated list are
evaluated only for their side effects. This example increments a list of
variables and uses the last one as the rvalue:
//: C03:CommaOperator.cpp
#include <iostream>
using namespace std;
int main() {
int a = 0, b = 1, c = 2, d = 3, e = 4;
a = (b++, c++, d++, e++);
cout << "a = " << a << endl;
// The parentheses are critical here. Without
// them, the statement will evaluate to:
(a = b++), c++, d++, e++;
cout << "a = " << a << endl;
} ///:~
In general, it’s best to avoid
using the comma as anything other than a separator, since people are not used to
seeing it as an
operator.
|
|