See the "Comma Operator ( , )" section on this page:
http://www.cplusplus.com/doc/tutorial/operators/
(also known as the "sequence operator" or even "binary sequence operator")
The comma does not end the statement. It is part of a longer statement which ends with a semi-colon.
When used with functions, the comma does the same things as calling the functions in separate statements.
start(), stop();
does the same as
start(); stop();
or
But note that you can not get at the return code of the first function unless you use an extra variable.
int ret = start(), stop();
will end up with the return code from stop, having thrown away the one from start().
And the example given as part of the comma operator explanation
1 2 3 4
|
int a = 0;
int b = 0;
a = (b=3, b+2);
|
is the same as
1 2 3 4 5
|
int a = 0;
int b = 0;
b=3;
a = b+2;
|
The example is a bit daft. Real code like that would be very annoying! But the comma operator is useful when initializing loop control variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <iostream>
using namespace std;
void process(char ch)
{
cout << ch;
}
int main()
{
const char val[] = "hello world";
for(size_t idx = 0, len = strlen(val); len > idx; ++idx)
{
process(val[idx]);
}
process('\n');
return 0;
}
|
This is better than
1 2 3
|
for(size_t idx = 0, strlen(val) > idx; ++idx)
{
...
|
(esp. for long strings) as you only calculate the length of the string once (the strlen function starts at the beginning and steps forward until it find the null term.)
And is better than
1 2 3 4 5
|
size_t len = strlen(val) ;
for(size_t idx = 0, len > idx; ++idx)
{
...
|
as len can only be seen inside the for loop's body (i.e. is tightly scoped)
Andy
PS also see
http://en.wikipedia.org/wiki/Comma_operator