increment operator in C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cuteanu
    New Member
    • Oct 2006
    • 14

    #1

    increment operator in C++

    how will the following code work
    int a=10;

    int i=a+a+++a++;
    cout<<i;
    the output is shown as 32 .
    while if the code would have been as follows:
    int i, a=10;
    i=a+a+++a++;
    cout<<i;
    the output is 30.
    why is this difference????
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by cuteanu
    why is this difference????
    You have seen a manifestation of "undefined behaviour". When you change
    the value of a variable more than once before a so called "sequence point"
    is reached, undefined behaviour will be the result. You increment the 'a'
    variable more than once before the ';' is reached. The ';' is a sequence point.

    Nothing can be said about the value of variable 'a'.

    kind regards,

    Jos

    Comment

    • cuteanu
      New Member
      • Oct 2006
      • 14

      #3
      Thanx,
      but tried many number of times, on different PC's the output remains the same.
      is it something to do with the dynamic declaration of the variable i??

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Originally posted by cuteanu
        Thanx,
        but tried many number of times, on different PC's the output remains the same.
        is it something to do with the dynamic declaration of the variable i??
        No as JosAH says you have invoked undefined behaviour, that is the reason for the difference. There is no need to try and explain the output further because it will be different on different platforms.

        As soon as you invoke undefined behaviour in a single line of a program the behaviour of the entire program becomes undefined, that it outputs anything vaguely sensible is in fact misleading, you can not rely on the output of this program.

        Comment

        Working...