I'm attempting to execute the following C code:
#include <stdio.h>
int a = 5;
int fun1(){
a = 17;
return 3;
}
int main(){
int b;
b = a + fun1();
printf("%d\n", b);
}
When I run it on my macbook I get an answer of 8, but when I run it in Linux I get an answer of 20. I've had a few friends run it and everyone with a Mac gets 8, while everyone running Linux gets 20. What would cause this?
I'm not so much interested in the correct answer as I am on the reason behind the two environments giving different answers. What about OS X and Linux causes the discrepancy?
The order of evaluation of parameters to operator +
is unspecified. That means that there is no particular ordering, and fun1()
can be evaluated before or after the read of a
in the expression a + fun1()
*. You are seeing the effect of different orders of evaluation on different platforms.
* Note that the function call fun1()
introduces a sequence point, so the behaviour of a + fun1();
is well defined, even if the order of evaluation of the operands is unspecified. Without a function call there would be no sequence point (e.g. a + a++
), which would yield undefined behaviour.
The order in which operands are evaluated is unspecified. That means in the expression a + fun1 () the compiler can choose to evaluate a before or after calling fun1 (). Both results are correct. Your code isn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With