-1

I am almost new to programming.

I see a lot of questions of this type in many question papers and exams

int j= 5;
int i=0;
i= j++ + ++j + j++ - ++j ;

I always predict the wrong value of variable 'i'. My friends suggested many approaches
but all fails in some or the other such expression.

Is there some universal rule/approach to evaluate such type of expressions?

newbie
  • 29
  • 4
  • 3
    Duplicate of many questions. Undefined behaviour; there is no right or wrong answer for the result. – Jonathan Leffler Oct 23 '13 at 04:25
  • 2
    Read [Why are these constructs undefined behavior?](http://stackoverflow.com/questions/949433/why-are-these-constructs-undefined-behavior) – Grijesh Chauhan Oct 23 '13 at 04:25
  • 1
    The universal rule is 'if a variable has its value modified more than once between sequence points, then the behaviour is undefined'. There are other ways to get undefined behaviour (`a[i++] = i;`, for example), but that covers this case. – Jonathan Leffler Oct 23 '13 at 04:28
  • 1
    Wikipedia page [http://en.wikipedia.org/wiki/Undefined_behavior][1] says that "ANSI C standard chose to leave similar constructions undefined" [1]: http://en.wikipedia.org/wiki/Undefined_behavior – Anurag Rana Oct 23 '13 at 04:41

1 Answers1

1

ANSI C explicitly refuses to make any guarantees about the order of argument evaluation for a n-ary operation. Therefore having

y = j++ + ++j

..you might end up with a logical equivalent of one of the following:

x1 = j++; x2 = ++j; y = x1 + x2

..or

x1 = ++j; x2 = j++; y = x1 + x2

depending on compiler, compiler version, OS, and even compilation flags. More complex expressions make things progressively more messy.

Alexander L. Belikoff
  • 5,698
  • 1
  • 25
  • 31