Pre-increment in C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Mindhunter74
    New Member
    • Oct 2009
    • 7

    Pre-increment in C++

    Why would the following statement assign 12 to x not 11?
    Code:
        int i=4;
        int x = (++i) + (++i);
        cout << x; // prints 12
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Everything within the parentheses are evaluated first. So i gets incremented twice before they're used to calculate the sum.

    Comment

    • horace1
      Recognized Expert Top Contributor
      • Nov 2006
      • 1510

      #3
      when ++ and -- are used in an expression such as
      Code:
      (i * j++) + (i * j)
      will the value of j in (i * j) be that before or after the increment in (i * j++)?
      In addition to evaluating the expression, the value of the variable in memory is altered (this is called a side effect). Do not use a variable more than once in an expression if one (or more) of the references has one of these operators attached to it. The standard does not specify the order in which the operands of an operator are evaluated and there is no guarantee when an affected variable will change its value. For example:
      Code:
       int i=2, j=3;
       printf("%d \n", (i * j++) + (i * j));
      on a Windows PC the gcc compiler prints 12 the Boralnd Turobo C V3 compiler prints 14.
      for we look at your example
      Code:
          int i=4;    
          int x = (++i) + (++i);
          cout << x; // prints 12
      the gcc compiler prints 12 the Boralnd Turobo C V3 compiler prints 11.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Actually that code can assign any value it wants to x because it exhibits undefined behaviour.

        Under undefined behaviour the program (and the compiler) are free to do absolutely anything it wants, no constraints are placed on it. Results could be anything from appearing to work correctly to producing an unexpected result to making demons fly out of your nose.

        What is more because the behaviour is undefined it does not even have to do the same thing when run another time.

        The reason this is undefined behaviour is that the code accesses a variable (i) is access between sequence points more than once where at least one of those accesses is to write its value.

        You should avoid undefined behaviour at all costs.

        Comment

        Working...