VS2005 is changing the order of functions calls depending on release/debug. Help!

Started by
4 comments, last by raccoonone 16 years, 3 months ago
Here's the problem. I have a program involving a lot of pseudo-random numbers. But depending on whether I compile for Release or Debug these numbers are being assigned in a different order, which is making it extremely difficult to debug. I created a simple test case that illustrates the problem: When I cast the value from rand() to a double and compile for Release the rand() calls are reversed. Anyone know how to fix this, so that the rand() calls remain in the same order, independent of Release/Debug mode?

#include "conio.h"
#include <stdlib.h>
#include <iostream>
using namespace std;

class MyClass_Double
{
public:
    double A, B;
    MyClass_Double(double a, double b) {A = a; B = b;}
};

class MyClass_Int
{
public:
    int A, B;
    MyClass_Int(int a, int b) {A = a; B = b;}
};

int main()
{
    //initialize with two random integers
    srand(7);
    MyClass_Double temp(rand(), rand());
    //reset rand(), so that the same numbers are generated
    srand(7);
    MyClass_Int temp2(rand(), rand());

    cout << "MyClass_Double.A = " << temp.A << ", MyClass_Double.B = " << temp.B << endl;
    cout << "MyClass_Int.A = " << temp2.A << ", MyClass_Int.B = " << temp2.B << endl;
    cout << "Press any key to continue.";
    while(!_kbhit());
    return 0;
}

Result of running the debug version:

MyClass_Double.A = 17422, MyClass_Double.B = 61
MyClass_Int.A = 17422, MyClass_Int.B = 61
Press any key to continue.

Result of running the release version:

MyClass_Double.A = 61, MyClass_Double.B = 17422
MyClass_Int.A = 17422, MyClass_Int.B = 61
Press any key to continue.

Advertisement
int a = rand();int b = rand();MyClass_Double temp(a, b);
Quote:Original post by SiCrane
int a = rand();int b = rand();MyClass_Double temp(a, b);


ya, I thought of doing that. But there are dozens, maybe hundreds of calls to rand() that I would have to change. So I was hoping for an easier solution, like a project setting that I could change.
Apparently C++ function call parameter evaluation order is not defined, so SiCrane's suggestion is probably the only solution.

C++ does not define evaluation order of function parameters.

In:
f( g(), h(), i(), j() )
, functions g,h,i and j may be evaluated in any order.

Same for operators:
std::cout << x() << y() << z();
, where x, y and z may be evaluated in any order, same for operators.

One solution to this is to use initialization lists:
class MyClass_Double{public:    double A, B;    MyClass_Double() 		: A(rand())		, B(rand())	{}};class MyClass_Int{public:    int A, B;    MyClass_Int() 				: A(rand())		, B(rand())	{}};
Here, C++ must evaluate the arguments in order of declaration.
Thanks for all the help! I guess it's time to make use of the Find feature.

This topic is closed to new replies.

Advertisement