Possible Duplicate:
C++ Comma Operator
I came across unexpected (to me at least) C++ behavior today, shown by the following snippit:
#include <iostream>
int main()
{
std::cout << ("1", "2") << std::endl;
return 0;
}
Output:
2
This works with any number of strings between the parentheses. Tested on the visual studio 2010 compiler as well as on codepad.
I'm wondering why this compiles in the first place, what is the use of this 'feature'?
The comma operator evaluates the expressions on both sides of the comma, but returns the result of the second.
Ahh, this is the comma operator. When you use a comma and two (or more) expressions, what happens is that all expressions are executed, and the result as a whole is the result of the last expression. That is why you get "2" as a result of this. See here for a bigger explanation.
Comma operator ( , ) The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.
For example, the following code:
Ref:http://www.cplusplus.com/doc/tutorial/operators/
The result of the comma (",") is the right subexpression. I use it in loops over stl containers:
It's called the comma operator: in an expression
x, y
, the compiler first evaluatesx
(including all side effects), theny
; the results of the expression are the results ofy
.In the expression you cite, it has absolutely no use; the first string is simply ignored. If the first expression has side effects, however, it could be useful. (Mostly for obfuscation, in my opinion, and it's best avoided.)
Note too that this only works when the comma is an operator. If it can be anything else (e.g. punctuation separating the arguments of a function), it is. So:
(See. I told you it was good for obfuscation.)