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#
  4. Incrementing and Decrementing - Just Trying to Understand

Incrementing and Decrementing - Just Trying to Understand

Scheduled Pinned Locked Moved C#
learningcomquestion
64 Posts 7 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.
  • N N8tiv

    I get the basic parts of incrementing and decrementing a variable by one. Maybe because I'm not quite thinking like a programmer yet, is why I don't understand this code below. "Console.WriteLine(y); // result = 99 — The value of y after" - this is what's confusing me. How do you get 99 when there is no loop? And doesn't 100 become 99 before you add it to 10? Of course after compiling this, it worked. It came from a book from BrainMeasures dot com. They said the book was even for novices (PSSH) Dummy it down for me quite a bit please. :-) LOL

    using System;

    class ArithmeticOperators
    {
    public static void Main()
    }
    int x = 10;
    int y = 100;
    int z = y-- + x;
    Console.WriteLine(z); // result = 110
    Console.WriteLine(y); // result = 99 — The value of y after
    // decrementing
    z = --z + x;
    Console.WriteLine(z); // result = 119
    }
    }

    My Coding Journey

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

    WidmarkRob wrote:

    Dummy it down for me quite a bit please.

    OK, let's break it down.

    WidmarkRob wrote:

    int x = 10;

    x is now 10.

    WidmarkRob wrote:

    int y = 100;

    y is now 100. Pretty obvious so far. But this

    WidmarkRob wrote:

    int z = y-- + x;

    is a weird thing, and in order to understand it, it is necessary to understand the difference between the result of an expression and the effect of an expression. The C# rules say this about post-decrement: "the operand is decremented. The result of the expression is the value the operand had before the decrement". (see operator --[^]) So what's happening here is that y is decremented (that is the effect), so after y-- has been evaluated y will be 99, but the value is the old y, 100 (that is the result). Then it goes on to add x to that result, no surprises there.

    WidmarkRob wrote:

    z = --z + x;

    This is different, a pre-decrement as it is called. The value of a pre-decrement is the new value, ie after the decrement. ps: most of this applies to most C-derived languages, except that C# is a bit special in that it specifies that the side-effects happen from left to right. That only matters if you decrement or increment something, and then use that same thing again in the same expression (ok not really, it's more complex, but it's True Enough)

    N 1 Reply Last reply
    0
    • L Lost User

      WidmarkRob wrote:

      did you see the part where I said I would understand if it was written the other way?

      Yes I saw that. That line of code would print 100 so it would not help you understand why y is 99 at all.

      N Offline
      N Offline
      N8tiv
      wrote on last edited by
      #8

      "Console.WriteLine(z); // result = 110" After reading the book, that line right there makes sense to me. It said something similar to, "you evaluate the expression before you do that decrement". I get that part, the way the expression was written I understand that. So when we write the next line to the console, "Console.WriteLine(y);" the variable y automagically turned into 99? y is declared at 100. I just don't see how it could automagically turn into 99 without some sort of loop. y-- is used in an expression, not used as a declared variable. I think that's where I'm getting confused. Maybe I've just seen too many YouTube videos where they are using incrementing and decrementing with loops. My Coding Journey

      L 1 Reply Last reply
      0
      • L Lost User

        WidmarkRob wrote:

        Dummy it down for me quite a bit please.

        OK, let's break it down.

        WidmarkRob wrote:

        int x = 10;

        x is now 10.

        WidmarkRob wrote:

        int y = 100;

        y is now 100. Pretty obvious so far. But this

        WidmarkRob wrote:

        int z = y-- + x;

        is a weird thing, and in order to understand it, it is necessary to understand the difference between the result of an expression and the effect of an expression. The C# rules say this about post-decrement: "the operand is decremented. The result of the expression is the value the operand had before the decrement". (see operator --[^]) So what's happening here is that y is decremented (that is the effect), so after y-- has been evaluated y will be 99, but the value is the old y, 100 (that is the result). Then it goes on to add x to that result, no surprises there.

        WidmarkRob wrote:

        z = --z + x;

        This is different, a pre-decrement as it is called. The value of a pre-decrement is the new value, ie after the decrement. ps: most of this applies to most C-derived languages, except that C# is a bit special in that it specifies that the side-effects happen from left to right. That only matters if you decrement or increment something, and then use that same thing again in the same expression (ok not really, it's more complex, but it's True Enough)

        N Offline
        N Offline
        N8tiv
        wrote on last edited by
        #9

        Okay, I think I got it now. When the decrementing comes after the variable. We evaluate the expression before the decrementing is applied. Then whenever we use the old declared variable after that first evaluated expression, the decrementing is applied. Is that right? My Coding Journey

        L 1 Reply Last reply
        0
        • N N8tiv

          "Console.WriteLine(z); // result = 110" After reading the book, that line right there makes sense to me. It said something similar to, "you evaluate the expression before you do that decrement". I get that part, the way the expression was written I understand that. So when we write the next line to the console, "Console.WriteLine(y);" the variable y automagically turned into 99? y is declared at 100. I just don't see how it could automagically turn into 99 without some sort of loop. y-- is used in an expression, not used as a declared variable. I think that's where I'm getting confused. Maybe I've just seen too many YouTube videos where they are using incrementing and decrementing with loops. My Coding Journey

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

          WidmarkRob wrote:

          the variable y automagically turned into 99?

          But it is not automagically turned in to 99 that is what the decrement operator does! And that is what I have been telling you. Take your code:

          int z = y-- + x;

          Substitute your values

          int z = 100-- + 10;

          The value of z is calculate right?

          100 + 10 = 110

          right? The then post decrement operator is applied to y so

          y = y - 1

          which make

          y = 99

          . Still not sure why you would think that you would need a loop to add or subtract anything.

          1 Reply Last reply
          0
          • N N8tiv

            Okay, I think I got it now. When the decrementing comes after the variable. We evaluate the expression before the decrementing is applied. Then whenever we use the old declared variable after that first evaluated expression, the decrementing is applied. Is that right? My Coding Journey

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

            Close enough. The decrementing itself really happens while that expression is being evaluated, but that rarely matters. It does matter if you do this:

            int x = 0;
            int z = x++ + ++x;

            After that, clearly x is 2, because it was incremented twice. And z is also 2, proving that the increment really happens while the expression is evaluated. First x++ is evaluated, the result is 0 and the effect is that x is now 1. Then ++x is evaluated, x was 1 and for pre-increment the result is the value after the increment, so the result is two (the effect is again that x is incremented, of course). So that works out to 0 + 2. The left-to-right rules goes even further, if you have an assignment where there's an increment on the left hand side (yes, you can do that), it happens before the right hand side is evaluated, which can be demonstrated with something like this:

            int[] array = new int[2];
            int x = 0;
            array[x++] = x++;

            After that, x is 2, obviously, and array looks like this: { 1, 0 } What happened, was the first x++ was evaluated first, making the index into the array 0, then the right hand side is evaluated, which is 1 due to the first increment, and then x is incremented again, and finally the value of the right hand side (which was 1) is stored in the array at index 0.

            N 2 Replies Last reply
            0
            • L Lost User

              Close enough. The decrementing itself really happens while that expression is being evaluated, but that rarely matters. It does matter if you do this:

              int x = 0;
              int z = x++ + ++x;

              After that, clearly x is 2, because it was incremented twice. And z is also 2, proving that the increment really happens while the expression is evaluated. First x++ is evaluated, the result is 0 and the effect is that x is now 1. Then ++x is evaluated, x was 1 and for pre-increment the result is the value after the increment, so the result is two (the effect is again that x is incremented, of course). So that works out to 0 + 2. The left-to-right rules goes even further, if you have an assignment where there's an increment on the left hand side (yes, you can do that), it happens before the right hand side is evaluated, which can be demonstrated with something like this:

              int[] array = new int[2];
              int x = 0;
              array[x++] = x++;

              After that, x is 2, obviously, and array looks like this: { 1, 0 } What happened, was the first x++ was evaluated first, making the index into the array 0, then the right hand side is evaluated, which is 1 due to the first increment, and then x is incremented again, and finally the value of the right hand side (which was 1) is stored in the array at index 0.

              N Offline
              N Offline
              N8tiv
              wrote on last edited by
              #12

              Because I'm Just Beginning, I'm going to stop at "Close Enough". I'm sure the book will eventually got into more details, but… For now, as long as they understand that basics. I think I can move on. Thank you for helping me understand this more, actually way mor. :-) My Coding Journey

              1 Reply Last reply
              0
              • L Lost User

                Close enough. The decrementing itself really happens while that expression is being evaluated, but that rarely matters. It does matter if you do this:

                int x = 0;
                int z = x++ + ++x;

                After that, clearly x is 2, because it was incremented twice. And z is also 2, proving that the increment really happens while the expression is evaluated. First x++ is evaluated, the result is 0 and the effect is that x is now 1. Then ++x is evaluated, x was 1 and for pre-increment the result is the value after the increment, so the result is two (the effect is again that x is incremented, of course). So that works out to 0 + 2. The left-to-right rules goes even further, if you have an assignment where there's an increment on the left hand side (yes, you can do that), it happens before the right hand side is evaluated, which can be demonstrated with something like this:

                int[] array = new int[2];
                int x = 0;
                array[x++] = x++;

                After that, x is 2, obviously, and array looks like this: { 1, 0 } What happened, was the first x++ was evaluated first, making the index into the array 0, then the right hand side is evaluated, which is 1 due to the first increment, and then x is incremented again, and finally the value of the right hand side (which was 1) is stored in the array at index 0.

                N Offline
                N Offline
                N8tiv
                wrote on last edited by
                #13

                :confused: after all that dumbing it down, I'm thrown for a loop (pun intended). After reading a little bit more in the book they decide to give me a little exercise. int x = 10; int y = 100; int z = y; y = y++ + x; z = ++z + x; I thought I would do this in my head before writing it to the console window. The first expression, the answer I got my head was: 110 (which turned out to be right, woo hoo) The second expression I got wrong, in my head I came up with: 121 the console window printed out: 111 Console.WriteLine(y); Console.WriteLine(z); just before this exercise, the book showed me a table trying to explain: primary, urnary, binary My Coding Journey

                L OriginalGriffO 2 Replies Last reply
                0
                • N N8tiv

                  :confused: after all that dumbing it down, I'm thrown for a loop (pun intended). After reading a little bit more in the book they decide to give me a little exercise. int x = 10; int y = 100; int z = y; y = y++ + x; z = ++z + x; I thought I would do this in my head before writing it to the console window. The first expression, the answer I got my head was: 110 (which turned out to be right, woo hoo) The second expression I got wrong, in my head I came up with: 121 the console window printed out: 111 Console.WriteLine(y); Console.WriteLine(z); just before this exercise, the book showed me a table trying to explain: primary, urnary, binary My Coding Journey

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

                  WidmarkRob wrote:

                  int z = y;

                  Ok, what happens here is not "make x an other word for y", which is what I think you might have thought. It really means "let x have the value that y now has". y later changed, z did not. Ok z did change, but the assignment to y did not affect it.

                  WidmarkRob wrote:

                  y = y++ + x;

                  does not affect z, only y.

                  1 Reply Last reply
                  0
                  • N N8tiv

                    :confused: after all that dumbing it down, I'm thrown for a loop (pun intended). After reading a little bit more in the book they decide to give me a little exercise. int x = 10; int y = 100; int z = y; y = y++ + x; z = ++z + x; I thought I would do this in my head before writing it to the console window. The first expression, the answer I got my head was: 110 (which turned out to be right, woo hoo) The second expression I got wrong, in my head I came up with: 121 the console window printed out: 111 Console.WriteLine(y); Console.WriteLine(z); just before this exercise, the book showed me a table trying to explain: primary, urnary, binary My Coding Journey

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

                    Try an experiment. When you see a statement involving prefix or postfix increments, mentally (or even physically) re-write it to be several statements, moving the increment outside all other statements.

                    y = y++ + x;

                    Becomes:

                    int y2 = y;
                    y = y + 1;
                    y = y2 + x;

                    In other words, the postfix increment of y is irrelevant, because the value is immediately discarded, and y is set to the value of the sum of the original value of y and x

                    z = ++z + x;

                    Becomes:

                    z = z + 1;
                    z = z + x;

                    That is all the compiler is doing - a prefix or suffix increment just gets done when it is met, that's all - it's syntactic sugar for the broken down statements above. Having said that, try not to use them in "complex" statements: What happens may not be what you expect - different compilers interpret "when to do this" slightly differently, and that gave have a dramatic effect. Normally, pre-and post- increments are kept to simple things like array accesses and for loops.

                    The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

                    "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

                    L N 2 Replies Last reply
                    0
                    • OriginalGriffO OriginalGriff

                      Try an experiment. When you see a statement involving prefix or postfix increments, mentally (or even physically) re-write it to be several statements, moving the increment outside all other statements.

                      y = y++ + x;

                      Becomes:

                      int y2 = y;
                      y = y + 1;
                      y = y2 + x;

                      In other words, the postfix increment of y is irrelevant, because the value is immediately discarded, and y is set to the value of the sum of the original value of y and x

                      z = ++z + x;

                      Becomes:

                      z = z + 1;
                      z = z + x;

                      That is all the compiler is doing - a prefix or suffix increment just gets done when it is met, that's all - it's syntactic sugar for the broken down statements above. Having said that, try not to use them in "complex" statements: What happens may not be what you expect - different compilers interpret "when to do this" slightly differently, and that gave have a dramatic effect. Normally, pre-and post- increments are kept to simple things like array accesses and for loops.

                      The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

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

                      OriginalGriff wrote:

                      different compilers interpret "when to do this" slightly differently

                      Not in C#. Or if they do, it's a compiler bug. There is only one right order of side-effects in C#, which is left-to-right.

                      OriginalGriffO 1 Reply Last reply
                      0
                      • L Lost User

                        OriginalGriff wrote:

                        different compilers interpret "when to do this" slightly differently

                        Not in C#. Or if they do, it's a compiler bug. There is only one right order of side-effects in C#, which is left-to-right.

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

                        I originally did add something to that effect, but deleted it because I didn't want to confuse the OP too much. Anyone who starts writing code like

                        int y = 10;
                        y = y++ + ++y*y--;

                        deserves the headache they are going to get1. 1 When I find out and hit them. 154, by the way.

                        The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

                        "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

                        L 1 Reply Last reply
                        0
                        • OriginalGriffO OriginalGriff

                          I originally did add something to that effect, but deleted it because I didn't want to confuse the OP too much. Anyone who starts writing code like

                          int y = 10;
                          y = y++ + ++y*y--;

                          deserves the headache they are going to get1. 1 When I find out and hit them. 154, by the way.

                          The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

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

                          Ok, but IMHO you could now be confusing the OP with the possibility that there's some sort of quantum-magic involved that makes the result depend on the phase of the moon or something..

                          OriginalGriffO 1 Reply Last reply
                          0
                          • L Lost User

                            Ok, but IMHO you could now be confusing the OP with the possibility that there's some sort of quantum-magic involved that makes the result depend on the phase of the moon or something..

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

                            Do you want to sit there and work out why y++ + ++y * y-- equals 154? Quantum magic works for me! :laugh:

                            The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

                            "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

                            L 1 Reply Last reply
                            0
                            • OriginalGriffO OriginalGriff

                              Do you want to sit there and work out why y++ + ++y * y-- equals 154? Quantum magic works for me! :laugh:

                              The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

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

                              Easy, 10 + 12 * 12. The complex cases don't really matter of course, I'm sure we're in agreement there - I just brought them into this to prove to OP that it really works that way.

                              OriginalGriffO 1 Reply Last reply
                              0
                              • L Lost User

                                Easy, 10 + 12 * 12. The complex cases don't really matter of course, I'm sure we're in agreement there - I just brought them into this to prove to OP that it really works that way.

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

                                :laugh: I know - but it's not that obvious when you look at it, particularly if you come from a C / C++ background where a different result is a strong possibility. DevC++ will give you 132 for example.

                                The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

                                "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

                                L 1 Reply Last reply
                                0
                                • L Lost User

                                  WidmarkRob wrote:

                                  It is declared at 100.

                                  Yes the initial value is 100, did you see the y--? As you were told, the -- is the decrement operator that makes y 99. The -- is short hand for y = y - 1.

                                  D Offline
                                  D Offline
                                  Dave Kreskowiak
                                  wrote on last edited by
                                  #22

                                  ThePhantomUpvoter wrote:

                                  The -- is short hand for y = y - 1

                                  That's not entirely correct. The point behind the '--' being in front of the expression or behind it just tells the compile WHEN to increment or decrement the expression. The operation is either going to happen before the expression is evaluated, in his case y, or after.

                                  A guide to posting questions on CodeProject[^]
                                  Dave Kreskowiak

                                  1 Reply Last reply
                                  0
                                  • OriginalGriffO OriginalGriff

                                    :laugh: I know - but it's not that obvious when you look at it, particularly if you come from a C / C++ background where a different result is a strong possibility. DevC++ will give you 132 for example.

                                    The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

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

                                    Also fun: different version of GCC give different results (usually 132 or 142).

                                    OriginalGriffO 1 Reply Last reply
                                    0
                                    • L Lost User

                                      Also fun: different version of GCC give different results (usually 132 or 142).

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

                                      Now you see why I hit people who do it! :laugh:

                                      The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

                                      "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

                                      K 1 Reply Last reply
                                      0
                                      • OriginalGriffO OriginalGriff

                                        Now you see why I hit people who do it! :laugh:

                                        The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

                                        K Offline
                                        K Offline
                                        Kenneth Haugland
                                        wrote on last edited by
                                        #25

                                        .. And if they turn the other cheek, hit them again :laugh: This has got to be close to using GoTo statments or possibly worse....

                                        OriginalGriffO L 2 Replies Last reply
                                        0
                                        • K Kenneth Haugland

                                          .. And if they turn the other cheek, hit them again :laugh: This has got to be close to using GoTo statments or possibly worse....

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

                                          I think of it as "Codefuscating" ;)

                                          The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

                                          "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

                                          K 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