MetricSystem93
MetricSystem93

Reputation: 61

C code produces different results on OS X vs Linux

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?

Upvotes: 6

Views: 2054

Answers (3)

capac
capac

Reputation: 11

There is no specification for how to evaluate these operands, so the compiler may choose either order. It seems in this case that the compiler you use on your Mac has a different implementation for evaluation order than the compiler on your Linux, thus the apparent inconsistency. Writing cleaner code greatly helps for things like this.

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227410

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.

Upvotes: 9

gnasher729
gnasher729

Reputation: 52538

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.

Upvotes: 4

Related Questions