Tuesday 31 January 2012

difference between i++ and ++i


i++ means 'tell me the value of i, then increment'
++i means 'increment i, then tell me the value'
For the prefix form:
  • x is evaluated to produce the variable
  • the value of the variable is copied to a temporary location
  • the temporary value is incremented to produce a new value (not overwriting the temporary!)
  • the new value is stored in the variable
  • the result of the operation is the new value
For the postfix form:
  • x is evaluated to produce the variable
  • the value of the variable is copied to a temporary location
  • the temporary value is incremented to produce a new value (not overwriting the temporary!)
  • the new value is stored in the variable
  • the result of the operation is the temporary copy

++i is definitiely as fast as i++ but it may be faster.
The reason is the implementation.
In order to implement i++ the implementation needs to generate a temporary copy of i unlike the implementation for ++i.
But smart compilers can optimize the genration of this temporary, they certainly do for POD types

No comments:

Post a Comment