15

I wrote the following code:

#include <iostream>
using namespace std;

int f()
{
    cout << "f()" << endl;
    return 3;
}

int v()
{
    cout << "v()" << endl;
    return 4;
}

int main()
{
    int m = f(),v();
    cout << m << endl;
    return 0;
}

I expected it to print:

f()
v()
3

compiling with g++ -O0 test.cpp -o test.out and running results:

f()
3

Why the call to v is omitted? (this can't be do to optimization, because I added the flag -O0)

Cœur
  • 34,719
  • 24
  • 185
  • 251
elyashiv
  • 3,529
  • 2
  • 27
  • 49
  • possible duplicate of [How does the Comma Operator work](http://stackoverflow.com/questions/54142/how-does-the-comma-operator-work) – Mohit Jain Jul 09 '15 at 13:10

2 Answers2

21
int m = f(),v(); 

This statement executes f() and assign return value to m, then declare function v() which return int type. int v(); also known as most vexing parse.

To achieve your comma operator test, try:

int m;
m = f(),v();
cout << m << endl;

see live sample.

user207421
  • 298,294
  • 41
  • 291
  • 462
billz
  • 43,318
  • 8
  • 77
  • 98
4

The following variation of your code demonstrates what this is doing:

http://ideone.com/GBae0p

#include <iostream>

int f() { std::cout << "f()" << std::endl; return 1; }

int main() {
   int t = f(), v();
   std::cout << t << std::endl;
   return 0;
}

This compiles without error, even though we don't have a "v()".

The comma operator is splitting this line

   int t = f(), v();

into

   int t = f();
   int v();

The second line is a function prototype which declares that there will be a function, int v(), which takes no parameters and returns an int.

It doesn't call it, it just pre-declares it - incase the compiler encounters a call it to it before it is actually defined - because the body is an empty statement (;). The compiler assumes we will implement it later or in a different compilation unit.

Because this commonly confuses experience and new programmers alike, because it is introduced by C++ allowing you to put function prototypes inside function bodies, this is called the most vexing parse.

kfsone
  • 22,620
  • 2
  • 39
  • 70