Thursday, May 10, 2007

Order of Evaluation of Functional Parameters

This question comes from one interview. What is the output for the following code?


int i=1;
printf("%d %d %d %d\n", i++, i++, i++, i++);


You are likely to say "1 2 3 4". Wrong! The correct answer (I think) should be we should never write code like this because the behavior is dependent on the platform.

The C programming language standards specifically allow the parameters to be passed to a function to be evaluated in any convenient order. The SUN Sparc station compiler worked left to right, which seems more natural, whereas the on FreeBSD, gcc worked right to left which may be more efficient in some circumstances, whereas on Mac OS X, expressions are from left to right, normal variables are valuated the last.

Consider the following program to prove my point.

#include
#include

int f1() {
printf("f1...\n");
return 1;
}
int f2() {
printf("f2...\n");
return 2;
}
int add(int i, int j) {
return i+j;
}
main() {
int i =1;
int j =1;
printf("%d %d %d %d\n", i++, i++, i++, i++);
printf("%d %d %d %d\n", j, j++, j++, j++);
add(f1(), f2());
}


Run it on FreeBSD (compiled with GCC),

$./printftest
4 3 2 1
4 3 2 1
f2...
f1...


Run it on Mac OS X Tiger (compiled with GCC),

$ ./printftest
1 2 3 4
4 1 2 3
f1...
f2...

1 comment:

torres said...

Hi

Tks very much for post:

I like it and hope that you continue posting.

Let me show other source that may be good for community.

Source: AT&T interview questions

Best rgs
David