Different output in GCC and Borland Turbo C for printf() statement

1.3k views Asked by At

I have a small code in C

#include<stdio.h>
int main()
{
    int a=10,b;
    b=a++ + ++a;
    printf("%d,%d,%d,%d",b,a++,a,++a);
    return 0;
}

Turbo C gives the following Output (as expected)

22,13,13,13

But GCC (used ubuntu and Code blocks compiler in windows) gives the following

22,13,14,14

I believe that Turbo c output was correct, but how come GCC is returning different output?

2

There are 2 answers

10
Rahul Tripathi On

This is an undefined behaviour. As in C there is no specification of function argument evaluation, so the compiler is free to do it in any way. It is undefined and arbitrary.

C99 standard 6.5.:-

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.

1
dhein On

They both are correct! This is undefined behavior, because you arent allowed to change the same value in a single invokation multiple times.

From c99 ISO/IEC 9899:TC3 -> Apenndix J:

J.2 Undefined behavior 1 The behavior is undefined in the following circumstances:

[...]

— Between two sequence points, an object is modified more than once, or is modified and the prior value is read other than to determine the value to be stored (6.5).

EDIT:

In reference to icepacks comment who told turbo c is predating c99, I added also the quote from the

C89 standard Programming Language C, X3.???-1988:

A.6.2 Undefined behavior The behavior in the following circumstances is undefined:

[..]

  • An object is modified more than once, or is modified and accessed other than to determine the new value, between two sequence points (3.3).