Tuesday 12 January 2010

Order of Evaluation of functions

Consider the following code:





//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

class
Base{
public
:
Base():x(0){};
int
incrAndGetX(void) {return ++x;};
int
decrAndGetX(void) {return --x;};
int
x;
};


int
Add(int a, int b)
{

return
(a+b);
}


int
Sub(int a, int b)
{

return
(a-b);
}


int
main()
{

Base b;
int
val1 = Add(b.incrAndGetX(), b.decrAndGetX());
int
val2 = Sub(b.incrAndGetX(), b.decrAndGetX());

cout<<"Val 1 = "<<val1<<endl;
cout<<"Val 2 = "<<val2<<endl;

return
0;
}







What is the output of the following program?

Depending on the compiler the output can be different. I tried it using the g++ and MSVC8 compilers and got the same result but the result cannot be guaranteed. I got the following output:

Val 1 = -1
Val 2 = 1

As you will notice that the order of evaluation is from right to left. Depending on the compiler and the platform the order of evaluation could be left to right, right to left or interleaved. The kind of problem shown in the program above can be dangerous as your code will work on 99% of the PCs and will fail on 1% and you will invest lots of time and resources to find and fix the problem.

There is an interesting discussion here on the same topic if you want to explore this topic further.

No comments:

Post a Comment