Search code examples
c++comma-operator

comma operator in c++ doesn't evaluate second expression


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)


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.