Two strings between brackets separated by a comma

2019-02-21 13:45发布

问题:

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'?

回答1:

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.



回答2:

It's called the comma operator: in an expression x, y, the compiler first evaluates x (including all side effects), then y; the results of the expression are the results of y.

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:

f( 1, 2 );      //  Call f with two arguments, 1 and 2
f( (1, 2) );    //  Call f with one argument, 2

(See. I told you it was good for obfuscation.)



回答3:

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:

a = (b=3, b+2);

Ref:http://www.cplusplus.com/doc/tutorial/operators/



回答4:

The result of the comma (",") is the right subexpression. I use it in loops over stl containers:

for( list<int>::iterator = mylist.begin(), it_end = mylist.end(); it != it_end; ++it )
  ...


回答5:

The comma operator evaluates the expressions on both sides of the comma, but returns the result of the second.