C/C++ Programming Puzzle
Tuesday April 8, 2008
It's been a while, so just to refresh you; what will this output?
#include
int fx(int * p) {
return (*p += 1) ;
}
int main()
{
int v=1;
printf("%d %d %d",v++,fx(&v),v) ;
return 0;
}
Answer in a couple of days...
- Link to C Tutorials


It SHOULD output
1 3 3
but if it is done in VS it will probably output
1 2 2
now to try it…
The about behavior is unknowable for ceratin by the standard I believe. The order of function argument evaluation is indeterminate and compiler specific. So it could output, 1 3 3, 2 2 1. Also unless rvo is applied or an r-value references being used as will be introduced by the new standard the returned int is a tempoarary.
it’s a classic problem related to the argument ‘order’. it seams that both the platform and compiler matters…
2 2 2 (X86_64/linux/gcc 3.4.5)
2 2 1 (X86/linux/gcc 2.96)
2 2 1 (X86/windows/vc6.0)
I find another interesting example:
#include
int
main (int argc, char **argv)
{
long i = 0;
printf (”%d %d %d %d %d %d %d %d %d %d\n”, i++, i++, i++, i++, i++, i++, i++, i++, i++, i++);
return 0;
}
x86_64(linux/gcc3.4) output:
4 3 2 1 0 9 8 7 6 5
x86(linux/gcc2.9) output:
9 8 7 6 5 4 3 2 1 0
x86(windows/vc6.0) output:
0 0 0 0 0 0 0 0 0 0
The result is undefined. When a variable is both read and written to more than once in the same sequence point the C standard says the behaviour is undefined.
ANSI C defines that the expressions are evaluated from right to left.
(think assembly… the caller function is supposed to push from right to left…)
So the output should be: 2 2 1.
Mind that v++ increments v after the push…
It is compiler specific.
In Solaris it should give the output as
2 2 3
But in VS it should give the o/p as
2 2 2
GCC/gcc(4.1.1) and MinGW/gcc(3.4.5) both give…
2 2 2
It should be 1 3 3
1 3 2
… 1 3 3
…oops, calculated the mistake as if the dereferenced value was only inside the scope of the function.
There is no correct output.
The ANSI C standard doesn’t guarantee the order in which parameters are evaluated when calling a function.
When values are mutated in the argument expressions and used more than once, the answer you get on your compiler is whatever was convenient on the architecture, calling convention and the compiler’s grammar.
the output of this program in gcc compiler is as:
2 2 1