Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Increment and Decrement Operators

Increment and Decrement Operators

Scheduled Pinned Locked Moved C / C++ / MFC
questionhelptutorial
24 Posts 8 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L Lost User

    I'm sorry but it is a well known fact that in expressions like this, the compiler is not constrained to follow the rules as you see them. Using multiple increment decrement operators in a single expression is not guaranteed to produce the result you expect and should not be used.

    Veni, vidi, abiit domum

    M Offline
    M Offline
    Marco Bertschi
    wrote on last edited by
    #6

    An undefined behavior often means that the compiler may crash, and if not it behaves like it thinks it should, which isn't necessarily the same on different compilers.

    Veni, vidi, caecus | Everything summarizes to Assembly code

    L 1 Reply Last reply
    0
    • T tgsb

      Hi everyone....this Increment(++) and Decrement(--) operators in C topic is really one of the surprise topic for me as I always get some surprise with their answer. The time I thought I got the concept of this topic I find my self wrong with its next question. I want to know what is its actual concept and whats the best approach to solve inc and dec operator questions. Make me understand with an example. Appreciate your suggestion and help. Thanks

      M Offline
      M Offline
      Marco Bertschi
      wrote on last edited by
      #7

      int i = 0;

      i++;

      Means that i is incremented after the statements execution

      ++i;

      Means that i is incremented before the statements execution The same is applicable on i-- and --i

      Veni, vidi, caecus | Everything summarizes to Assembly code

      1 Reply Last reply
      0
      • M Marco Bertschi

        An undefined behavior often means that the compiler may crash, and if not it behaves like it thinks it should, which isn't necessarily the same on different compilers.

        Veni, vidi, caecus | Everything summarizes to Assembly code

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #8

        Yes. My comments were an over-simplification, but it is still worth avoiding expressions of that sort.

        Veni, vidi, abiit domum

        M 1 Reply Last reply
        0
        • L Lost User

          Yes. My comments were an over-simplification, but it is still worth avoiding expressions of that sort.

          Veni, vidi, abiit domum

          M Offline
          M Offline
          Marco Bertschi
          wrote on last edited by
          #9

          Richard MacCutchan wrote:

          but it is still worth avoiding expressions of that sort.

          Every respectable Dev must avoid it. By the way, my comment was intended to be an addition to yours.

          Veni, vidi, caecus | Everything summarizes to Assembly code

          L 1 Reply Last reply
          0
          • S Suk nta

            hey i want to rectify Message send by Richard MacCutchan

            int i = 10;
            int result;
            result = i++; // result equals 10, i equals 11
            result = ++i; // result equals 12, i equals 12
            result = i--; // result equals 12, i equals 11
            result = --i; // result equals 10, i equals 10

            // note do not use expressions such as
            result = ++i + i++; // results undefined

            As written the last line gives output undefine i think its wrong .it will give correct output as 23. If u had checked then u already got the result. here i will explan u how it's work.. 1:from left to right ++i changes i values 10 to 11. 2:then it will add 11 + 11 (as i++ is post increment operator it will execute after expression execution) and gives result as 22 3: then i values becomes 22 and i++ will going to execute and i value changes to 22+1=23

            D Offline
            D Offline
            David Crow
            wrote on last edited by
            #10

            sukanta kumar mangal wrote:

            As written the last line gives output undefine i think its wrong .it will give correct output as 23.
            If u had checked then u already got the result.
            here i will explan u how it's work..

            At a minimum, you might want to brush up on sequence points.

            "One man's wage rise is another man's price increase." - Harold Wilson

            "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

            "Show me a community that obeys the Ten Commandments and I'll show you a less crowded prison system." - Anonymous

            1 Reply Last reply
            0
            • S Suk nta

              hey i want to rectify Message send by Richard MacCutchan

              int i = 10;
              int result;
              result = i++; // result equals 10, i equals 11
              result = ++i; // result equals 12, i equals 12
              result = i--; // result equals 12, i equals 11
              result = --i; // result equals 10, i equals 10

              // note do not use expressions such as
              result = ++i + i++; // results undefined

              As written the last line gives output undefine i think its wrong .it will give correct output as 23. If u had checked then u already got the result. here i will explan u how it's work.. 1:from left to right ++i changes i values 10 to 11. 2:then it will add 11 + 11 (as i++ is post increment operator it will execute after expression execution) and gives result as 22 3: then i values becomes 22 and i++ will going to execute and i value changes to 22+1=23

              R Offline
              R Offline
              Ron Beyer
              wrote on last edited by
              #11

              I'll explain why the behavior is undefined... This has a lot to do with operator precedence[^], see the ++ as a prefix operator has an equal precedence to the + operator. Its up to the compiler to determine which one to evaluate first, since they are at an equal precedence there is no universal "++(pre) before +". However, ++ as a postfix operator has a higher precedence than the prefix operator, so for example: i = 10 result = ++i + i++; Turns into result = ++i + 11; Now, the compiler really doesn't care which one is evaluated first, the + or the ++. Each one is free to implement it as they see fit, so it might be 22 or it might be 23, it depends on which one the programmer handled first.

              S 1 Reply Last reply
              0
              • R Ron Beyer

                I'll explain why the behavior is undefined... This has a lot to do with operator precedence[^], see the ++ as a prefix operator has an equal precedence to the + operator. Its up to the compiler to determine which one to evaluate first, since they are at an equal precedence there is no universal "++(pre) before +". However, ++ as a postfix operator has a higher precedence than the prefix operator, so for example: i = 10 result = ++i + i++; Turns into result = ++i + 11; Now, the compiler really doesn't care which one is evaluated first, the + or the ++. Each one is free to implement it as they see fit, so it might be 22 or it might be 23, it depends on which one the programmer handled first.

                S Offline
                S Offline
                Suk nta
                wrote on last edited by
                #12

                no no..in any compiler prefix operator execute first than postfix. postfix will execute after value returned or assigned to some variable..

                L 1 Reply Last reply
                0
                • T tgsb

                  Hi everyone....this Increment(++) and Decrement(--) operators in C topic is really one of the surprise topic for me as I always get some surprise with their answer. The time I thought I got the concept of this topic I find my self wrong with its next question. I want to know what is its actual concept and whats the best approach to solve inc and dec operator questions. Make me understand with an example. Appreciate your suggestion and help. Thanks

                  T Offline
                  T Offline
                  tgsb
                  wrote on last edited by
                  #13

                  O God....wow I am not the only one who is confused? This is the problem I specified when I started this thread, I got surprising answers when i solve these inc and dec problems.So who is correct please tell me and whom explaination I go with to pursue my learning on this topic?

                  OriginalGriffO 1 Reply Last reply
                  0
                  • M Marco Bertschi

                    Richard MacCutchan wrote:

                    but it is still worth avoiding expressions of that sort.

                    Every respectable Dev must avoid it. By the way, my comment was intended to be an addition to yours.

                    Veni, vidi, caecus | Everything summarizes to Assembly code

                    L Offline
                    L Offline
                    Lost User
                    wrote on last edited by
                    #14

                    Marco Bertschi wrote:

                    my comment was intended to be an addition to yours.

                    Yes, that was how I understood it. :thumbsup:

                    Veni, vidi, abiit domum

                    1 Reply Last reply
                    0
                    • S Suk nta

                      no no..in any compiler prefix operator execute first than postfix. postfix will execute after value returned or assigned to some variable..

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #15

                      See http://msdn.microsoft.com/en-us/library/126fe14k.aspx[^].

                      Veni, vidi, abiit domum

                      1 Reply Last reply
                      0
                      • T tgsb

                        O God....wow I am not the only one who is confused? This is the problem I specified when I started this thread, I got surprising answers when i solve these inc and dec problems.So who is correct please tell me and whom explaination I go with to pursue my learning on this topic?

                        OriginalGriffO Offline
                        OriginalGriffO Offline
                        OriginalGriff
                        wrote on last edited by
                        #16

                        Pre- and post- fix increment and decrement operations are pretty easy in theory, it's only when people get creative that you get problems in practice. Basically, a prefix (++i or --i) says to increase or decrease the value before you use the variable, so the variable has the new value immediately:

                        i = 10;
                        x = ++i + 5;

                        Can be read as:

                        i = 10;
                        i = i + 1;
                        x = i + 5;

                        and similarly for the -- version:

                        i = 10;
                        x = --i + 5;

                        Can be read as:

                        i = 10;
                        i = i - 1;
                        x = i + 5;

                        The postfix version (i++ or i--) does the same thing, but after the variable has been used:

                        i = 10;
                        x = i++ + 5;

                        Can be read as:

                        i = 10;
                        x = i + 5;
                        i = i + 1;

                        And similarly

                        i = 10;
                        x = i-- + 5;

                        Can be read as:

                        i = 10;
                        x = i + 5;
                        i = i - 1;

                        The trouble comes when you start mixing operations on the same line (as Richard said):

                        i = 10;
                        x = ++i + i++;

                        The problem is that the language specification does not define exactly when pre- and post- fix operations should occur! Which means that it's implementation specific exactly what you get as a result: The value of i should always be the same: 12 but the value of x can be different depending on the compiler (and to an extent on the target processor - ARM for example has built in pre- and post- fix increment and decrement to it's "machine code" LOAD operations, so it would be quite likely that an efficient compiler would use them directly) Should it be executed as:

                        i = 10;
                        i = i + 1;
                        x = i + i;
                        i = i + 1;

                        Which gives the result 22 or as

                        i = 10;
                        i1 = i;
                        i = i + 1;
                        x = i1 + i;
                        i = i + 1;

                        Which gives 21 Or as

                        i = 10;
                        i1 = i;
                        i = i + 1;
                        x = i + i1;
                        i = i + 1;

                        which also gives 21 by a different route And bear in mind that the compiler does not have to evaluate the two operands of "+" in left to right order, so it could even give some very strange and unexpected results! Like 23... So avoid combining them: use them for "simple expressions" such as incrementing an array index each time round a loop, but don't get fancy, or your code may well fail in interesting ways... :laugh:

                        Never underestimate the power of stupid things in large numbers --- Serious Sam

                        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                        T 1 Reply Last reply
                        0
                        • S Suk nta

                          hey i want to rectify Message send by Richard MacCutchan

                          int i = 10;
                          int result;
                          result = i++; // result equals 10, i equals 11
                          result = ++i; // result equals 12, i equals 12
                          result = i--; // result equals 12, i equals 11
                          result = --i; // result equals 10, i equals 10

                          // note do not use expressions such as
                          result = ++i + i++; // results undefined

                          As written the last line gives output undefine i think its wrong .it will give correct output as 23.
                          If u had checked then u already got the result.
                          here i will explan u how it's work..

                          1:from left to right ++i changes i values 10 to 11.
                          2:then it will add 11 + 11 (as i++ is post increment operator it will execute after expression execution) and gives result as 22
                          3: then i values becomes 22 and i++ will going to execute and i value changes to 22+1=23

                          OriginalGriffO Offline
                          OriginalGriffO Offline
                          OriginalGriff
                          wrote on last edited by
                          #17

                          You are making unwarranted assumptions! :laugh: It's more complex that that - Richard is right, you shouldn't mix 'em - see my post below for some compiler nasties...

                          Never underestimate the power of stupid things in large numbers --- Serious Sam

                          "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                          "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                          S 1 Reply Last reply
                          0
                          • OriginalGriffO OriginalGriff

                            Pre- and post- fix increment and decrement operations are pretty easy in theory, it's only when people get creative that you get problems in practice. Basically, a prefix (++i or --i) says to increase or decrease the value before you use the variable, so the variable has the new value immediately:

                            i = 10;
                            x = ++i + 5;

                            Can be read as:

                            i = 10;
                            i = i + 1;
                            x = i + 5;

                            and similarly for the -- version:

                            i = 10;
                            x = --i + 5;

                            Can be read as:

                            i = 10;
                            i = i - 1;
                            x = i + 5;

                            The postfix version (i++ or i--) does the same thing, but after the variable has been used:

                            i = 10;
                            x = i++ + 5;

                            Can be read as:

                            i = 10;
                            x = i + 5;
                            i = i + 1;

                            And similarly

                            i = 10;
                            x = i-- + 5;

                            Can be read as:

                            i = 10;
                            x = i + 5;
                            i = i - 1;

                            The trouble comes when you start mixing operations on the same line (as Richard said):

                            i = 10;
                            x = ++i + i++;

                            The problem is that the language specification does not define exactly when pre- and post- fix operations should occur! Which means that it's implementation specific exactly what you get as a result: The value of i should always be the same: 12 but the value of x can be different depending on the compiler (and to an extent on the target processor - ARM for example has built in pre- and post- fix increment and decrement to it's "machine code" LOAD operations, so it would be quite likely that an efficient compiler would use them directly) Should it be executed as:

                            i = 10;
                            i = i + 1;
                            x = i + i;
                            i = i + 1;

                            Which gives the result 22 or as

                            i = 10;
                            i1 = i;
                            i = i + 1;
                            x = i1 + i;
                            i = i + 1;

                            Which gives 21 Or as

                            i = 10;
                            i1 = i;
                            i = i + 1;
                            x = i + i1;
                            i = i + 1;

                            which also gives 21 by a different route And bear in mind that the compiler does not have to evaluate the two operands of "+" in left to right order, so it could even give some very strange and unexpected results! Like 23... So avoid combining them: use them for "simple expressions" such as incrementing an array index each time round a loop, but don't get fancy, or your code may well fail in interesting ways... :laugh:

                            Never underestimate the power of stupid things in large numbers --- Serious Sam

                            T Offline
                            T Offline
                            tgsb
                            wrote on last edited by
                            #18

                            Thanks sir for highlighting its deep concepts related to the compiler. I hope now I am able to solve these question without getting shocked by their answers. Appreciate all your responses.

                            OriginalGriffO 1 Reply Last reply
                            0
                            • T tgsb

                              Thanks sir for highlighting its deep concepts related to the compiler. I hope now I am able to solve these question without getting shocked by their answers. Appreciate all your responses.

                              OriginalGriffO Offline
                              OriginalGriffO Offline
                              OriginalGriff
                              wrote on last edited by
                              #19

                              You're welcome!

                              Never underestimate the power of stupid things in large numbers --- Serious Sam

                              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                              "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                              1 Reply Last reply
                              0
                              • OriginalGriffO OriginalGriff

                                You are making unwarranted assumptions! :laugh: It's more complex that that - Richard is right, you shouldn't mix 'em - see my post below for some compiler nasties...

                                Never underestimate the power of stupid things in large numbers --- Serious Sam

                                S Offline
                                S Offline
                                Suk nta
                                wrote on last edited by
                                #20

                                I know increment and decrement operator depend on compiler. actually i had tried it in dev c++.

                                OriginalGriffO 1 Reply Last reply
                                0
                                • S Suk nta

                                  I know increment and decrement operator depend on compiler. actually i had tried it in dev c++.

                                  OriginalGriffO Offline
                                  OriginalGriffO Offline
                                  OriginalGriff
                                  wrote on last edited by
                                  #21

                                  If you know that something is compiler dependant, then you can't say "it is like this" - because there is a very good chance that the other person is not using the same compiler! :laugh:

                                  Never underestimate the power of stupid things in large numbers --- Serious Sam

                                  "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                                  "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                                  S 1 Reply Last reply
                                  0
                                  • L Lost User

                                    These operators merely add (inc) or subtract (dec) 1 from the item in question. If the operator is used in the postfix position (i++) then the original value is returned. If the operator is used in the prefix position (--i) then the new value is returned. Thus:

                                    int i = 10;
                                    int result;
                                    result = i++; // result equals 10, i equals 11
                                    result = ++i; // result equals 12, i equals 12
                                    result = i--; // result equals 12, i equals 11
                                    result = --i; // result equals 10, i equals 10

                                    // note do not use expressions such as
                                    result = ++i + i++; // results undefined

                                    Veni, vidi, abiit domum

                                    S Offline
                                    S Offline
                                    Stefan_Lang
                                    wrote on last edited by
                                    #22

                                    Am I the only one to spot that at least one of the problems in your last line is not related to increment and decrement at all? The operator+ which is invoked here needs to evaluate both of its operands, but it's undefined whether the first or second operand is evaluated first - the compiler may choose to do either! So, if the compiler evaluates the first operand first, the following happens:

                                    i = 10;
                                    i = i + 1; // pre-increment of the first argument
                                    first_arg = i;
                                    second_arg = i;
                                    i = i + 1; // post-increment of the second argument
                                    result = first_arg + second_arg; // 11 + 11

                                    Now consider the same on the assumption the compiler evaluates the second operand first:

                                    i = 10;
                                    second_arg = i;
                                    i = i + 1; // post-increment of second argument
                                    i = i + 1; // pre-increment of first argument
                                    first_arg = 1;
                                    result = first_arg + second_arg; // 12 + 10

                                    In this case, the results are the same, but that is just by coincidence - if you had used subtraction in stead of addition you'd be in for a surprise! You may want to check http://en.cppreference.com/w/cpp/language/eval_order[^] for further information regarding both function argument evaluation and increment/decrement.

                                    GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                                    L 1 Reply Last reply
                                    0
                                    • S Stefan_Lang

                                      Am I the only one to spot that at least one of the problems in your last line is not related to increment and decrement at all? The operator+ which is invoked here needs to evaluate both of its operands, but it's undefined whether the first or second operand is evaluated first - the compiler may choose to do either! So, if the compiler evaluates the first operand first, the following happens:

                                      i = 10;
                                      i = i + 1; // pre-increment of the first argument
                                      first_arg = i;
                                      second_arg = i;
                                      i = i + 1; // post-increment of the second argument
                                      result = first_arg + second_arg; // 11 + 11

                                      Now consider the same on the assumption the compiler evaluates the second operand first:

                                      i = 10;
                                      second_arg = i;
                                      i = i + 1; // post-increment of second argument
                                      i = i + 1; // pre-increment of first argument
                                      first_arg = 1;
                                      result = first_arg + second_arg; // 12 + 10

                                      In this case, the results are the same, but that is just by coincidence - if you had used subtraction in stead of addition you'd be in for a surprise! You may want to check http://en.cppreference.com/w/cpp/language/eval_order[^] for further information regarding both function argument evaluation and increment/decrement.

                                      GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                                      L Offline
                                      L Offline
                                      Lost User
                                      wrote on last edited by
                                      #23

                                      That was exactly my point.

                                      Veni, vidi, abiit domum

                                      1 Reply Last reply
                                      0
                                      • OriginalGriffO OriginalGriff

                                        If you know that something is compiler dependant, then you can't say "it is like this" - because there is a very good chance that the other person is not using the same compiler! :laugh:

                                        Never underestimate the power of stupid things in large numbers --- Serious Sam

                                        S Offline
                                        S Offline
                                        Suk nta
                                        wrote on last edited by
                                        #24

                                        Thanks

                                        1 Reply Last reply
                                        0
                                        Reply
                                        • Reply as topic
                                        Log in to reply
                                        • Oldest to Newest
                                        • Newest to Oldest
                                        • Most Votes


                                        • Login

                                        • Don't have an account? Register

                                        • Login or register to search.
                                        • First post
                                          Last post
                                        0
                                        • Categories
                                        • Recent
                                        • Tags
                                        • Popular
                                        • World
                                        • Users
                                        • Groups