Search code examples
cgccstandardsturbo-c

pre and post increment operations on a variable give different output on TC and gcc


Here is my simple code ...

#include<stdio.h>
int main()
{
int i=5;
printf("%d %d %d %d %d ",i++,i--,++i,--i,i);
return 0;
}

On gcc,it gives output as '4 5 5 5 5'

but on TC,it gives output as '4 5 5 4 5'

what I know that in printf statement,evaluation will be from left to right if it is a single expression but in normal statement,it will be from left to right.

but if printf contain multiple expressions,then evaluation will be on stack,the elements would be pushed onto stack from left to right but popped out from right to left and that justified the TC output

Please correct me where am I wrong ???


Solution

  • C does not specify which order function arguments should be evaluated in, and so it is undefined and a compiler can do it however they choose, including arbitrarily and randomly. Bjarne Stroustrup says this explicitly in "The C++ Programming Language" 3rd edition section 6.2.2

    He also gives a reason:

    Better code can be generated in the absence of restrictions on expression evaluation order