Question

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)

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top