Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two strings between brackets separated by a comma in C++ [duplicate]

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

like image 557
Adversus Avatar asked Aug 10 '12 09:08

Adversus


4 Answers

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.

like image 61
Lyubomir Vasilev Avatar answered Oct 06 '22 04:10

Lyubomir Vasilev


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.)

like image 23
James Kanze Avatar answered Oct 06 '22 05:10

James Kanze


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 )
  ...
like image 30
Alexander Chertov Avatar answered Oct 06 '22 06:10

Alexander Chertov


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/

like image 22
Lwin Htoo Ko Avatar answered Oct 06 '22 05:10

Lwin Htoo Ko