2

I stumbled upon some code today, I simplified it to this :

#include <iostream>
using std::cout;
using std::cin;

bool changeX(int &x)
{
    x = 5;
    return true;
}

void printvals(bool bval, int intval)
{
    cout << bval << " : " << intval;
}

int main()
{
    int x;
    printvals(changeX(x), x);
    cin.get();
}

Here, x is still uninitialized at the time it's passed to the function printvals but can I say for sure that x will always be initialized before printvals uses it? I tried to run my simplified code in VS2013 debug-mode which gave me : Run-Time Check Failure #3 - The variable 'x' is being used without being initialized.. However, running it in release-mode ran fine and printed : 1 : 5 as expected.

Does this meant that I can use this approach in production code? Will x always be initialized before printvals can use it so it doesn't cause UB?

Hatted Rooster
  • 33,170
  • 5
  • 52
  • 104
  • possible duplicate of [Compilers and argument order of evaluation in C++](http://stackoverflow.com/questions/621542/compilers-and-argument-order-of-evaluation-in-c) โ€“ Cory Kramer Jan 14 '15 at 16:10

4 Answers4

9

can I say for sure that x will always be initialized before printvals uses it?

No, the order of evaluation of function parameters is unspecified. Since you may read from an uninitialized variable, your code may have undefined behaviour. You cannot rely on the side effects of the call to changeX.

juanchopanza
  • 210,243
  • 27
  • 363
  • 452
4

The order of evaluation of arguments in a function is unspecified, so NO, you cannot say that.

See e.g. http://en.cppreference.com/w/cpp/language/eval_order

or see the standard if you dare read "standardese" :)

PS: even if the order may have been specified, it is always a good idea to avoid code like this, since most of the time other people reading your code will have exactly the same question, and will lose a lot of time digging in. Just prefer clarity over extremely "clever" code.

vsoftco
  • 52,188
  • 7
  • 109
  • 221
  • Heh, the standardese here is remarkably straightforward, see [my answer](http://stackoverflow.com/a/27947714/2069064). It's actually almost verbatim your first sentence :) โ€“ Barry Jan 14 '15 at 16:26
  • @Barry, indeed, finally a piece of straightforward english ;) โ€“ vsoftco Jan 14 '15 at 16:27
1

This could lead to undefined behavior, since order of execution is unspecified (it depends on the compiler).

Lawrence Aiello
  • 4,204
  • 5
  • 17
  • 31
1

This is one of those places where the C++ standard is extremely easy to understand. From ยง8.3.6/9 (in N3797, emphasis mine):

The order of evaluation of function arguments is unspecified.

That means you cannot rely on intval being evaluated as a copy of x after changeX() is called. Your code is thus undefined behavior.

Barry
  • 247,587
  • 26
  • 487
  • 819