1

I ran a C program and got different output on different C compilers. Below is my program

void main()
{
    int i=5;
     printf("%d%d%d%d%d",i++,i--,++i,--i,i);
}

ON boarnland c++ complier o/p is

45545

and on gcc its

45555

is it really compiler dependent or its OS dependent?

The arguments in a function call are pushed into the stack from left to right. The evaluation is by popping out from the stack. and the evaluation is from right to left, hence the result.

Reno
  • 33,594
  • 11
  • 89
  • 102
Amit Singh Tomar
  • 8,380
  • 27
  • 120
  • 199
  • Doesn't appear to be the OS. I would say it was the compiler. – Randall Hunt Feb 25 '11 at 09:39
  • Combining effects and side-effects of different operations in to one terse codeline like this makes your code hard to read, IMNSHO. I would avoid it for readability alone. (I only use ++ and -- in well-established idioms such as for-loops or stand-alone) – Rolf Rander Feb 25 '11 at 09:44

1 Answers1

5

You cannot rely on the order of execution of side effects to arguments to a function. In this case the 2 compilers are executing the side effects in a different order, producing different results.

qbert220
  • 11,220
  • 4
  • 31
  • 31
  • Thanks @qbert but i really don't konw about side effects ,i would like to read about side effects ...where can i read about it?? – Amit Singh Tomar Feb 25 '11 at 09:43
  • nd whts the order of execution in 2 compliler?? – Amit Singh Tomar Feb 25 '11 at 09:44
  • @AMIT: The "++" and "--" can cause side effects. These are things that happen after the value of the expression has been used. i++ means take the value of i, then increment i. In this case the incrementation of i is called a side effect. – qbert220 Feb 25 '11 at 09:54