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. Other Discussions
  3. The Weird and The Wonderful
  4. How to increment a variable [modified]

How to increment a variable [modified]

Scheduled Pinned Locked Moved The Weird and The Wonderful
tutorial
22 Posts 8 Posters 5 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 Luc Pattyn

    I do remember IBM mainframes batch processing Fortran jobs (actually Watfor/Watfiv), punched on Hollerith cards, read one by one by a noisy machine, compiled one by one (no intermediate storage), listed one by one on an even noisier line printer, with each student allotted 5 minutes of execution time, for a total of one hour a day; the remainder of the day the uni needed its mainframe for its own IT handling. In 5 minutes the huge machine performed much less than a typical desktop would do today in 1 second. The good thing was the compile and link stages were not time-limited, and the compilers tried to maximize the number and meaningfulness of the messages it emitted. :)

    Luc Pattyn [Forum Guidelines] [My Articles]


    - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets


    R Offline
    R Offline
    Robert Surtees
    wrote on last edited by
    #9

    You forgot to mention the keypunches never had a ribbon with ink so your deck of cards were completly blank making inserting and modifing the code next to impossible. (and we did it while walking uphill in the pouring rain). :) My favorite was taking the compiler course (Dragon Book) using an IBM 1130 [^]running I think Fortran 66 -- only arithmatic IF for conditional processing. IF( expression ) 100, 200, 300 Fun.

    1 Reply Last reply
    0
    • L Luc Pattyn

      Kurdy Malloy wrote:

      It made me wonders if the compiler was smart enough to ...

      We can only hope the compiler generates code compatible with the language specification; i++ is a post-increment operator, it increments after the main operation (=) got executed. It isn't a compiler's duty to guess at what the programmer intended, it should do so only when reporting error and warning messages ("Are you missing a ;"). :)

      Luc Pattyn [Forum Guidelines] [My Articles]


      - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets


      C Offline
      C Offline
      CurtD
      wrote on last edited by
      #10

      In c++, VS 2005, the unoptimized code is actually kind of stupid i = i++; mov eax,dword ptr [i (40904Ch)] mov dword ptr [i (40904Ch)],eax mov ecx,dword ptr [i (40904Ch)] add ecx,1 mov dword ptr [i (40904Ch)],ecx It gets i, stores it in i, gets i, increments i, stores it in i. Not sure why it thinks it needs to do the first 2 steps. When I turn on "optimized for speed" (not comfort like me) it generates the exact same (smart) code as ++i;

      L S 2 Replies Last reply
      0
      • C CurtD

        In c++, VS 2005, the unoptimized code is actually kind of stupid i = i++; mov eax,dword ptr [i (40904Ch)] mov dword ptr [i (40904Ch)],eax mov ecx,dword ptr [i (40904Ch)] add ecx,1 mov dword ptr [i (40904Ch)],ecx It gets i, stores it in i, gets i, increments i, stores it in i. Not sure why it thinks it needs to do the first 2 steps. When I turn on "optimized for speed" (not comfort like me) it generates the exact same (smart) code as ++i;

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #11

        the stoopit code is pretty normal since i=i++; falls apart in i=i; and i++; and that is what the assembly code does, without any optimization. :)

        Luc Pattyn [Forum Guidelines] [My Articles]


        - before you ask a question here, search CodeProject, then Google - the quality and detail of your question reflects on the effectiveness of the help you are likely to get - use the code block button (PRE tags) to preserve formatting when showing multi-line code snippets


        1 Reply Last reply
        0
        • C CurtD

          In c++, VS 2005, the unoptimized code is actually kind of stupid i = i++; mov eax,dword ptr [i (40904Ch)] mov dword ptr [i (40904Ch)],eax mov ecx,dword ptr [i (40904Ch)] add ecx,1 mov dword ptr [i (40904Ch)],ecx It gets i, stores it in i, gets i, increments i, stores it in i. Not sure why it thinks it needs to do the first 2 steps. When I turn on "optimized for speed" (not comfort like me) it generates the exact same (smart) code as ++i;

          S Offline
          S Offline
          supercat9
          wrote on last edited by
          #12

          When I turn on "optimized for speed" (not comfort like me) it generates the exact same (smart) code as ++i; Wouldn't a more efficient implementation be to simply do nothing, given the lack of a sequence point between the increment and the assignment? Not that I'd generally expect a compiler to find that optimization, but I would have expected code like:

          mov eax,[_i] ; Fetch value before increment
          inc dword [_i] ; Do increment
          mov [_i],eax ; Store fetched value

          which would, of course, effectively do nothing. BTW, is there any guarantee about the behavior of "do_something(var++)" if do_something references var? What about "i=++i"? Even though it's hard to imagine that "i=++i;" would do anything other than increment "i", I don't think there's any guarantee that it won't?

          C 1 Reply Last reply
          0
          • S supercat9

            When I turn on "optimized for speed" (not comfort like me) it generates the exact same (smart) code as ++i; Wouldn't a more efficient implementation be to simply do nothing, given the lack of a sequence point between the increment and the assignment? Not that I'd generally expect a compiler to find that optimization, but I would have expected code like:

            mov eax,[_i] ; Fetch value before increment
            inc dword [_i] ; Do increment
            mov [_i],eax ; Store fetched value

            which would, of course, effectively do nothing. BTW, is there any guarantee about the behavior of "do_something(var++)" if do_something references var? What about "i=++i"? Even though it's hard to imagine that "i=++i;" would do anything other than increment "i", I don't think there's any guarantee that it won't?

            C Offline
            C Offline
            CurtD
            wrote on last edited by
            #13

            supercat9 wrote:

            Wouldn't a more efficient implementation be to simply do nothing, given the lack of a sequence point between the increment and the assignment? Not that I'd generally expect a compiler to find that optimization, but I would have expected code like: mov eax,[_i] ; Fetch value before increment inc dword [_i] ; Do increment mov [_i],eax ; Store fetched valuewhich would, of course, effectively do nothing. BTW, is there any guarantee about the behavior of "do_something(var++)" if do_something references var? What about "i=++i"? Even though it's hard to imagine that "i=++i;" would do anything other than increment "i", I don't think there's any guarantee that it won't?

            This code doesn't "do nothing" i = i++; It still has to inc i and store it in i. It is just a long form of ++i; The VS optimizer usually does a pretty good job. I had to heavily optimize some code a few years ago. I don't remember which VS version I was using, but I was impressed with the code it came up with. In this case it generates mov eax,1 add dword ptr [i],eax This seems a little strange to me. Maybe an "add" is much faster than an "inc". It's been a while since I was optimizing asm code. do_something(var++) is going to push the current var on the stack, call do_something, then inc var. Nothing strange about that.

            S 2 Replies Last reply
            0
            • C CurtD

              supercat9 wrote:

              Wouldn't a more efficient implementation be to simply do nothing, given the lack of a sequence point between the increment and the assignment? Not that I'd generally expect a compiler to find that optimization, but I would have expected code like: mov eax,[_i] ; Fetch value before increment inc dword [_i] ; Do increment mov [_i],eax ; Store fetched valuewhich would, of course, effectively do nothing. BTW, is there any guarantee about the behavior of "do_something(var++)" if do_something references var? What about "i=++i"? Even though it's hard to imagine that "i=++i;" would do anything other than increment "i", I don't think there's any guarantee that it won't?

              This code doesn't "do nothing" i = i++; It still has to inc i and store it in i. It is just a long form of ++i; The VS optimizer usually does a pretty good job. I had to heavily optimize some code a few years ago. I don't remember which VS version I was using, but I was impressed with the code it came up with. In this case it generates mov eax,1 add dword ptr [i],eax This seems a little strange to me. Maybe an "add" is much faster than an "inc". It's been a while since I was optimizing asm code. do_something(var++) is going to push the current var on the stack, call do_something, then inc var. Nothing strange about that.

              S Offline
              S Offline
              supercat9
              wrote on last edited by
              #14

              CurtD wrote:

              do_something(var++) is going to push the current var on the stack, call do_something, then inc var. Nothing strange about that.

              Really? The compiler I tested performed the increment before the function call.

              C 1 Reply Last reply
              0
              • S supercat9

                CurtD wrote:

                do_something(var++) is going to push the current var on the stack, call do_something, then inc var. Nothing strange about that.

                Really? The compiler I tested performed the increment before the function call.

                C Offline
                C Offline
                CurtD
                wrote on last edited by
                #15

                From MSDN When a postfix operator is applied to a function argument, the value of the argument is not guaranteed to be incremented or decremented before it is passed to the function. See section 1.9.17 in the C++ standard for more information. So, like so much in life, you just roll the dice and take your chances.

                1 Reply Last reply
                0
                • C CurtD

                  supercat9 wrote:

                  Wouldn't a more efficient implementation be to simply do nothing, given the lack of a sequence point between the increment and the assignment? Not that I'd generally expect a compiler to find that optimization, but I would have expected code like: mov eax,[_i] ; Fetch value before increment inc dword [_i] ; Do increment mov [_i],eax ; Store fetched valuewhich would, of course, effectively do nothing. BTW, is there any guarantee about the behavior of "do_something(var++)" if do_something references var? What about "i=++i"? Even though it's hard to imagine that "i=++i;" would do anything other than increment "i", I don't think there's any guarantee that it won't?

                  This code doesn't "do nothing" i = i++; It still has to inc i and store it in i. It is just a long form of ++i; The VS optimizer usually does a pretty good job. I had to heavily optimize some code a few years ago. I don't remember which VS version I was using, but I was impressed with the code it came up with. In this case it generates mov eax,1 add dword ptr [i],eax This seems a little strange to me. Maybe an "add" is much faster than an "inc". It's been a while since I was optimizing asm code. do_something(var++) is going to push the current var on the stack, call do_something, then inc var. Nothing strange about that.

                  S Offline
                  S Offline
                  supercat9
                  wrote on last edited by
                  #16

                  CurtD wrote:

                  This code doesn't "do nothing"

                  If the variable i is equal to five before the statement, "i = i++;" is executed, would it not be legitimate for the compiler's generated code to read i (five), increment i (yielding and storing six), and then store the read value back to i (setting it back to 5)? If the variable i is not volatile, would not a legitimate optimization thus be to eliminate the statement altogether? Out of curiosity, I wonder if there are any compilers which do not always update a variable used with a pre-increment before making use of the pre-incremented value? It's possible to contrive examples where the optimal code would in fact use (var+1) in the expression and then later store the incremented value to the variable, but I doubt compilers would find such optimizations.

                  C 1 Reply Last reply
                  0
                  • S supercat9

                    CurtD wrote:

                    This code doesn't "do nothing"

                    If the variable i is equal to five before the statement, "i = i++;" is executed, would it not be legitimate for the compiler's generated code to read i (five), increment i (yielding and storing six), and then store the read value back to i (setting it back to 5)? If the variable i is not volatile, would not a legitimate optimization thus be to eliminate the statement altogether? Out of curiosity, I wonder if there are any compilers which do not always update a variable used with a pre-increment before making use of the pre-incremented value? It's possible to contrive examples where the optimal code would in fact use (var+1) in the expression and then later store the incremented value to the variable, but I doubt compilers would find such optimizations.

                    C Offline
                    C Offline
                    CurtD
                    wrote on last edited by
                    #17

                    supercat9 wrote:

                    If the variable i is equal to five before the statement, "i = i++;" is executed, would it not be legitimate for the compiler's generated code to read i (five), increment i (yielding and storing six), and then store the read value back to i (setting it back to 5)? If the variable i is not volatile, would not a legitimate optimization thus be to eliminate the statement altogether?

                    Well, according to MSDN, the C++ standard does not define the proper behavior when a postfix is applied to a function arg. If anyone knows why they decided to leave it up to the compiler writers instead of deciding on a "standard", I would love to know the reason. The best thing to do is not write code like this. MSDN doesn't say specifically how a postfix is supposed to behave in the example i = i++. But, VS 2005 inc's i before storing it in i -- I assume because of operator precedence.

                    supercat9 wrote:

                    Out of curiosity, I wonder if there are any compilers which do not always update a variable used with a pre-increment before making use of the pre-incremented value? It's possible to contrive examples where the optimal code would in fact use (var+1) in the expression and then later store the incremented value to the variable, but I doubt compilers would find such optimizations.

                    When playing with this example, the optimizer did just that in one case -- it kept (i+1) in a reg, used it a few times, and stored it later. The VS compiler will optimize away code that doesn't do anything.

                    void donothing()
                    {
                    int i = 5;
                    i++;
                    }

                    No code is generated for donothing() and any call to it is ignored.

                    C 1 Reply Last reply
                    0
                    • C CurtD

                      supercat9 wrote:

                      If the variable i is equal to five before the statement, "i = i++;" is executed, would it not be legitimate for the compiler's generated code to read i (five), increment i (yielding and storing six), and then store the read value back to i (setting it back to 5)? If the variable i is not volatile, would not a legitimate optimization thus be to eliminate the statement altogether?

                      Well, according to MSDN, the C++ standard does not define the proper behavior when a postfix is applied to a function arg. If anyone knows why they decided to leave it up to the compiler writers instead of deciding on a "standard", I would love to know the reason. The best thing to do is not write code like this. MSDN doesn't say specifically how a postfix is supposed to behave in the example i = i++. But, VS 2005 inc's i before storing it in i -- I assume because of operator precedence.

                      supercat9 wrote:

                      Out of curiosity, I wonder if there are any compilers which do not always update a variable used with a pre-increment before making use of the pre-incremented value? It's possible to contrive examples where the optimal code would in fact use (var+1) in the expression and then later store the incremented value to the variable, but I doubt compilers would find such optimizations.

                      When playing with this example, the optimizer did just that in one case -- it kept (i+1) in a reg, used it a few times, and stored it later. The VS compiler will optimize away code that doesn't do anything.

                      void donothing()
                      {
                      int i = 5;
                      i++;
                      }

                      No code is generated for donothing() and any call to it is ignored.

                      C Offline
                      C Offline
                      CurtD
                      wrote on last edited by
                      #18

                      For more fun from the C++ standard: [ Example: i = v[i++]; // the behavior is undefined i = 7, i++, i++; // i becomes 9 i = ++i + 1; // the behavior is undefined i = i + 1; // the value of i is incremented —end example ] I think the best programming practice is to avoid "undefined" behavior.

                      modified on Tuesday, March 24, 2009 2:43 PM

                      1 Reply Last reply
                      0
                      • L Lost User

                        It was in release mode of course otherwise it's only normal that it wouldn't do any optimizations :) Ok didn't think of volatile - well then "any variable or field that is not volatile" can have an assignment to itself removed without any harm (unless you're doing scary reflection tricks..) But the JIT compiler is a problem.. how can you see what code it produces?

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

                        Hey, The CLR ships with a tool called NGen. NGen compiles IL into native code so if you use this you will be able to see what code is produced :) Hope that helps

                        At university studying Software Engineering - if i say this line to girls i find they won't talk to me Dan

                        1 Reply Last reply
                        0
                        • R Robert Surtees

                          Luc Pattyn wrote:

                          It isn't a compiler's duty to guess at what the programmer intended, it should do so only when reporting error and warning messages ("Are you missing a ;").

                          Waaay back in the good old days at University we were blessed / cursed with using a PL/C compiler. It was a student version of the full PL/I compiler and was guaranteed to always produce some sort of output regardless of how stupid your input was. This was a good thing as often you only got one chance a day (yes kids, that is one chance a day) to see if your program would compile and work. The results were often spectacular with pages of fanfold shooting out of the line printer.

                          T Offline
                          T Offline
                          Tom Delany
                          wrote on last edited by
                          #20

                          "Oh, I see by your variable name that you intended this to be an unsigned imaginary number. Level of certainty: 95%" That's not actually what the output said, but that's an example of the kind of thing that I imagined the compiler saying that as it was processing the code. I do seem to recall it giving some kind of "level of certainty".

                          We are dyslexic of Borg. Refutance is systile. Your a$$ will be laminated!

                          R 1 Reply Last reply
                          0
                          • T Tom Delany

                            "Oh, I see by your variable name that you intended this to be an unsigned imaginary number. Level of certainty: 95%" That's not actually what the output said, but that's an example of the kind of thing that I imagined the compiler saying that as it was processing the code. I do seem to recall it giving some kind of "level of certainty".

                            We are dyslexic of Borg. Refutance is systile. Your a$$ will be laminated!

                            R Offline
                            R Offline
                            Robert Surtees
                            wrote on last edited by
                            #21

                            That's right. It was somewhat conversational with a hint of arrogant superiority. You wrote "this" (you bonehead). PL/C chooses to do "this". If smileys had been invented then I'm sure it would have followed with a :P

                            1 Reply Last reply
                            0
                            • L Lost User

                              It was in release mode of course otherwise it's only normal that it wouldn't do any optimizations :) Ok didn't think of volatile - well then "any variable or field that is not volatile" can have an assignment to itself removed without any harm (unless you're doing scary reflection tricks..) But the JIT compiler is a problem.. how can you see what code it produces?

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

                              I don't like to think what would happen to "i = i++" if "i" is truely volatile. Would the post increment be actioned on an interrupt modified value? Now that would be a good bug to find!

                              "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
                              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