2 Replies - 925 Views - Last Post: 19 December 2008 - 10:32 AM Rate Topic: -----

#1 amitdhar  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 49
  • Joined: 01-February 08

increment order

Post icon  Posted 19 December 2008 - 09:45 AM

int a=10,c;
c=++a + a + ++a/a++ + a;
cout<<c;



the above segment theoritcaly gives 36, but practicaly it is giving 37.

Could anyone please make me understand the sequence of execution performed in the above calculation?
Is This A Good Question/Topic? 0
  • +

Replies To: increment order

#2 GWatt  Icon User is online

  • member icon

Reputation: 274
  • View blog
  • Posts: 3,072
  • Joined: 01-December 05

Re: increment order

Posted 19 December 2008 - 10:13 AM

The first thing that happens is the pre-increment is evaluated.
++a happens twice which makes a 12.
second, a is divided by a which yields 1.
third the additive operators are evaluated. you have three 12's and one 1, so the answer is 37.
finally, the post-increment (a++) is evaluated bringing the value of a to 13.

This post has been edited by GWatt: 19 December 2008 - 10:14 AM

Was This Post Helpful? 0
  • +
  • -

#3 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 856
  • View blog
  • Posts: 2,339
  • Joined: 20-August 07

Re: increment order

Posted 19 December 2008 - 10:32 AM

Note that this is all undefined behaviour. Theoretically, there is no correct value, because there is no defined evaluation order for these kinds of expressions (The outcome depends entirely on your compiler)

This post has been edited by Bench: 19 December 2008 - 10:33 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1