-5

Here is the C program which is giving different output depending on Compiler used:

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

Check the output on the following link.

http://imgur.com/z9aMSwj,Vwx3P9S

http://imgur.com/z9aMSwj,Vwx3P9S#1

My question is what is the technical reason that output is different?

Akash Rana
  • 3,685
  • 3
  • 19
  • 28

3 Answers3

0

The technical reason is that there is no defined behaviour for such an operation, allowing compilers to handle this kind of an order as they wish. Such cases are generally referred as Undefined Behaviour.

Utkan Gezer
  • 3,009
  • 2
  • 16
  • 29
0

According to C language, expressions like ++i + i++ + ++i + i++ have undefined behavior.

Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34
  • There are a lot of questions asked in placement papers of this type, so can you please tell me what should be my approach to deal with these questions? – Akash Rana Mar 10 '14 at 17:57
  • @user3402873 get familiar with the concept of sequence points http://en.wikipedia.org/wiki/Sequence_point – Arjun Sreedharan Mar 10 '14 at 18:01
0

In a i++ expression, two things happen. First, the expression is evaluated to i, then i is incremented later. The behaviour of 'later' is undefined. If there are 4 such expressions in a statement, there are countless possible orders to evaluate the increments and decrements.

SzG
  • 12,333
  • 4
  • 28
  • 41