Search code examples
c++stringparenthesescomma-operator

Two strings between brackets separated by a comma in C++


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


Solution

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