Search code examples
cgccturbo-c

A weird behavior of C compilers GCC and Turbo


I've gone through other similar questions, but trying to understand the situation I'm facing.

So, here's my two line C code.

int i=0;
printf("%d %d %d %d %d",i++,i--,++i,--i,i);

And here are the outputs I get from GCC and Turbo C Compiler.

GCC

Output:

-1 0 0 0 0

Turbo C

Output:

-1 0 0 -1 0

I tried all sorts of experiments with pre-increment operator individually, and both compilers work similar but when I use above printf statement, output differs.

I know that Turbo C is age-old compiler and now obsolete and non-standard but still can't get an idea what's wrong with above code.


Solution

  • It's undefined behavior, you're both reading and modifying i multiple times without a sequence point. (The , in the function parameter list is not a sequence point, and the order of evaluation of function arguments is not defined either.)

    The compiler can output whatever it wants in this situation. Don't do that.

    Find a whole host of other similar issues by search this site for [C] undefined behavior. It's quite enlightening.