-4

If int x=5;I suppose the expression y=++x * ++x; is evaluated as:

First execute ++x causing x=6 and then again ++x causing x=7 the expression then evaluates y=x*x making the value of y=49 Using same reasoning the following lines of code

int z=5, x=5,y=0,p=0;
y=++x * ++x + ++x;
p= ++z + ++z * ++z;

should have evaluated same values of y and p but the compiler produces different answer. I probably there is something I am missing in the order of precedence.

pranphy
  • 1,787
  • 4
  • 16
  • 22
  • You should **never code `++x * ++x`** because that is **undefined bhavior** and the implementation is allowed to do anything (including exploding the computer, or even doing what you was naively expecting) – Basile Starynkevitch Mar 16 '13 at 15:13

1 Answers1

3

Both of your expressions cause undefined behaviour by trying to modify a value more than once without an intervening sequence point. There is no general answer to your question.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • why should the compiler produce same set of consistent results on every compilation then? There can't be anything random, physics prevents that! – pranphy Mar 16 '13 at 15:27
  • 1
    @PrakashGautam "Even compiler producing same set of consistent results for an undefined behaviour" is also undefined behaviour !! – Barath Ravikumar Mar 16 '13 at 15:35
  • 1
    @PrakashGautam Nobody said the result will be random, it can be anything - that's what "undefined behaviour" means – qrdl Mar 16 '13 at 15:36