1

I understand the problems with the classic example of

int i=0;
foo(i++, i++);

but I can't convince myself of whether the following is valid or invalid

int foo(int& i)
{
   i=42;
   return 99;
}

bar(foo(i), i);

I understand that the order 'foo(i)' and 'i' are evaluated is undefined, but what exactly does 'evaluated' mean? i.e. will the 2nd parameter of bar always be 42, or can the current value of 'i' be passed in before foo changes it?

Tam Toucan
  • 137
  • 10

2 Answers2

4

No it is not guaranteed.
The order of evaluation of arguments to an function is Unspecified[Ref 1].
It can be possible that either:

  • foo(i) gets evaluated first or
  • i gets evaluated or
  • any other magical order(in case number of arguments were more than two)

Unspecified in this context means the implementation is allowed to implement the said feature whichever way they want and it need not be documented.


[Ref 1]
C++03 5.2.2 Function call Para 8

The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations take effect before the function is entered. The order of evaluation of the postfix expression and the argument expression list is unspecified.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

This sample (gcc 4.6)

#include <iostream>
using namespace std;

int foo(int& i)
{
    i=42;
    return 99;
}

void bar(int i, int j)
{
    cout << "i = " << i << "; j = " << j << endl;
}

int main()
{
    int i =10;
    bar(foo(i), i);
    return 0;
}

gives i = 99, j = 10.

So it is really not guaranteed.

Viktor Latypov
  • 14,289
  • 3
  • 40
  • 55