Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C code produces different results on OS X vs Linux

Tags:

c

linux

macos

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?

like image 568
MetricSystem93 Avatar asked Apr 08 '15 19:04

MetricSystem93


2 Answers

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.

like image 167
juanchopanza Avatar answered Sep 20 '22 18:09

juanchopanza


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.

like image 29
gnasher729 Avatar answered Sep 21 '22 18:09

gnasher729