Gotcha No. 2
This article will come up with the resolution for a classical interview question that even you could have when applying for a c++ programming position. The logic behind this is that the C++ standard is very liberal when it comes about interpreting arguments passed to functions. See the following source, and of course the question is: What will be printed…
#include <iostream>
int f (int a, int b, int c)
{
std::cout << "a="<<a<<" b="<<b<<" c="<<c<<std::endl;
return a+b+c;
}
int main()
{
int i = 1;
std::cout<<"f="<<f(i++, i++, i++)<<std::endl<<"i="<<i<<std::endl;
}
There is no correct answer to this question, you have to be aware of this kind of behaviour. Now see the outputs:
Microsoft Visual C++ 2005 Express Edition:
a=1 b=1 c=1
f=3
i=4
As you can see, the values are not incremented before they are sent to the function, so the function still sees the original '1'. The calue of i gets updated after the function call, so this is why we have the correct result '4'.
Microsoft VS.NET 2003
a=3 b=2 c=1
f=6
i=4
So, the parameters are evaluated before the function call… Interesting that two compilers that are from the same company, and are considered to be the most up-to-date to the C++ standard produce so different behaviors…
Now, to my big surprise, Digital Mars (8.49) produced something like:
f=a=3 b=2 c=1
6
i=4
This was definitely not what I expected from a decent compiler… You judge it for yourself… It somehow interpreted the stream in a linear way without evaluating the whole command… Strange.
The GCC3.4.2 produced:
a=3 b=2 c=1
f=6
i=4
This looks fairly well for me, accepted.
Borland's CBuilder (and the BCC55 and the quite dinosaur, but freely downloadable TurboC 1.01 (from 1990)) kicked me off the chair again…
a=3 b=2 c=1
f=6
i=1
For God's sake… what happened with the three times incremented 'i' value??? After the function is called it's already 4, not one… It seemed to me, the Borland Compilers have updated the value of 'i' only after the ';' which ended the command because when I have printed in a separate cout afterwards it was 4… Interesting way of a working, mechanism. But not necessarily correct.
Compilers tested
MS.NET 2003
VS 2005 Express
Digital Mars 8.49
Borland CBuilder 6
BCC 55
Turbo C 1.01
GCC 3.4.2
(c) 2007 fritzone