Search code examples
c++operator-precedence

Order of evaluation example


I'm trying to set in my mind once and for all how expressions are being evaluated. And with this quest of mine I came up with this example which I don't know what to make of.

#include <iostream>
using namespace std;
typedef void(*func)(int);

void r( int i )
{
    cout << i << endl;
}
func f( int i )
{
   cout << i << endl;
   return &r;
}

int main()
{
   int i = 0;
   f(++i)(++i);
   return 0;
}

Having this piece of code compiled with MVSC 2008 will produce this output: 2 2. The same code but compiled with gcc 4.8.1 will raise an warning(operation on i may be undefined) and will produce this output: 1 2.

What I'm trying to understand is why gcc 4.8.1 considers that there might be a case of undefined behavior? The side-effects of both pre-increments are sequenced relative to each other.

Cheers, Andrei


Solution

  • The side-effects of both pre-increments are sequenced relative to each other.

    No they're not. Each argument evaluation is sequenced before its function call, and the function calls are sequenced with each other; but both could be evaluated before the first call, in which case there's nothing to sequence them with each other.