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.
  • 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
            • 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....

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

              Worse. With goto at least only one thing can happen, even if it's not always immediately clear what that thing is.

              K 1 Reply Last reply
              0
              • OriginalGriffO OriginalGriff

                I think of it as "Codefuscating" ;)

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

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

                To you or the compiler or perhaps both? :laugh:

                OriginalGriffO 1 Reply Last reply
                0
                • L Lost User

                  Worse. With goto at least only one thing can happen, even if it's not always immediately clear what that thing is.

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

                  I have seen some pretty nasty goto's in my life, but I have to agree that this seems to take the cake. Why would anybody want to use such a feature anyway, it seems daft.

                  1 Reply Last reply
                  0
                  • K Kenneth Haugland

                    To you or the compiler or perhaps both? :laugh:

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

                    Oh just me, the compiler knows what it's doing. I just guess. :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

                      Oh just me, the compiler knows what it's doing. I just guess. :laugh:

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

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

                      Quote:

                      I just guess. debug.

                      FTFY

                      1 Reply Last reply
                      0
                      • 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

                        K Offline
                        K Offline
                        Keld Olykke
                        wrote on last edited by
                        #32

                        Hi, Sometimes a simple description can be very hard to grasp - especially if the simple description tries to abstract the details away. In such cases I find it rewarding simply to dig a bit deeper... Here goes the details:

                        .entrypoint
                        // Code size 51 (0x33)
                        .maxstack 3
                        .locals init ([0] int32 x,
                        [1] int32 y,
                        [2] int32 z)
                        IL_0000: nop // evaluation stack is empty []
                        // int x = 10;
                        IL_0001: ldc.i4.s 10 // push 10 onto stack [10]
                        IL_0003: stloc.0 // pop 10 into x []
                        // int y = 100;
                        IL_0004: ldc.i4.s 100 // push 100 onto stack [100]
                        IL_0006: stloc.1 // pop 100 into y []
                        // int z = y-- + x;
                        IL_0007: ldloc.1 // push y onto stack [100]
                        IL_0008: dup // copy top stack value onto stack [100,100]
                        IL_0009: ldc.i4.1 // push 1 onto stack [1,100,100]
                        IL_000a: sub // y-- [99,100]
                        IL_000b: stloc.1 // pop 99 into y [100]
                        IL_000c: ldloc.0 // push x onto stack [10,100]
                        IL_000d: add // + x [110]
                        IL_000e: stloc.2 // pop 110 into z []

                        If instruction, stack and arithmic unit are alien terms to you, then above might be a bit tough. It is a window into a lower layer of code. The C# compiler outputs this in binary form as your assembly/executable. IL means Intermediate Language and it can be executed by a Virtual Machine aka a program. The idea is to simulate the arithmic unit of a cpu, so above code is also a window into history. -- and ++ are special language features that comes nearly for free because of the (virtual) machine architecture. I produced above from your code example by running IL Disassembly from Microsft .Net. Kind Regards, Keld Ølykke

                        N 1 Reply 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)

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

                          I see you guys have been busy bees about this… I had to take a break, steam was coming from my ears because of this. Anyway, I looked over the example in the exercise they gave me. Give me about 30 min., I'll explain to you guys but I ended up getting the second expression in my exercise wrong. By the way, thank you for trying to help clear this up for me. Rob My Coding Journey

                          1 Reply Last reply
                          0
                          • K Keld Olykke

                            Hi, Sometimes a simple description can be very hard to grasp - especially if the simple description tries to abstract the details away. In such cases I find it rewarding simply to dig a bit deeper... Here goes the details:

                            .entrypoint
                            // Code size 51 (0x33)
                            .maxstack 3
                            .locals init ([0] int32 x,
                            [1] int32 y,
                            [2] int32 z)
                            IL_0000: nop // evaluation stack is empty []
                            // int x = 10;
                            IL_0001: ldc.i4.s 10 // push 10 onto stack [10]
                            IL_0003: stloc.0 // pop 10 into x []
                            // int y = 100;
                            IL_0004: ldc.i4.s 100 // push 100 onto stack [100]
                            IL_0006: stloc.1 // pop 100 into y []
                            // int z = y-- + x;
                            IL_0007: ldloc.1 // push y onto stack [100]
                            IL_0008: dup // copy top stack value onto stack [100,100]
                            IL_0009: ldc.i4.1 // push 1 onto stack [1,100,100]
                            IL_000a: sub // y-- [99,100]
                            IL_000b: stloc.1 // pop 99 into y [100]
                            IL_000c: ldloc.0 // push x onto stack [10,100]
                            IL_000d: add // + x [110]
                            IL_000e: stloc.2 // pop 110 into z []

                            If instruction, stack and arithmic unit are alien terms to you, then above might be a bit tough. It is a window into a lower layer of code. The C# compiler outputs this in binary form as your assembly/executable. IL means Intermediate Language and it can be executed by a Virtual Machine aka a program. The idea is to simulate the arithmic unit of a cpu, so above code is also a window into history. -- and ++ are special language features that comes nearly for free because of the (virtual) machine architecture. I produced above from your code example by running IL Disassembly from Microsft .Net. Kind Regards, Keld Ølykke

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

                            Okay, just to recap… I'm going to show the example they gave me first… Then tell you how I understand what you guys have been trying to help me with. Then I will post my exercise towards the end and try to explain how I came up with my answer doing it in my head before running the program and printing it to the console window.

                            // Example 3-2.cs
                            // Increment and Decrement
                            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
                            }
                            }

                            So, we print out the variable z… Like it says, the result is 110. Okay, easy enough. Just in my mind, the variable y automagically becomes 99. Anyway, you guys have explained to me that the variable y takes on the new value after evaluating the expression. Semi-sort of easy enough. Using this as somewhat of a template for my exercise is probably what threw me off. In the exercise, I got the first expression done in my head correctly. Meaning it matched what the console window printed out. The second expression, using the example above. I also thought the variable y would become the new value after evaluating the first expression. That's why in my head, I came up with 121… The console window printed out 111. Drill 3-1 Start with the following assignments: int x = 10; int y = 100; int z = y; Then write a C# program to compute and display the values of the variables y and z after executing these expressions: y = y++ + x; z = ++z + x; My Online Journey

                            L 1 Reply Last reply
                            0
                            • N N8tiv

                              Okay, just to recap… I'm going to show the example they gave me first… Then tell you how I understand what you guys have been trying to help me with. Then I will post my exercise towards the end and try to explain how I came up with my answer doing it in my head before running the program and printing it to the console window.

                              // Example 3-2.cs
                              // Increment and Decrement
                              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
                              }
                              }

                              So, we print out the variable z… Like it says, the result is 110. Okay, easy enough. Just in my mind, the variable y automagically becomes 99. Anyway, you guys have explained to me that the variable y takes on the new value after evaluating the expression. Semi-sort of easy enough. Using this as somewhat of a template for my exercise is probably what threw me off. In the exercise, I got the first expression done in my head correctly. Meaning it matched what the console window printed out. The second expression, using the example above. I also thought the variable y would become the new value after evaluating the first expression. That's why in my head, I came up with 121… The console window printed out 111. Drill 3-1 Start with the following assignments: int x = 10; int y = 100; int z = y; Then write a C# program to compute and display the values of the variables y and z after executing these expressions: y = y++ + x; z = ++z + x; My Online Journey

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

                              WidmarkRob wrote:

                              int z = y-- + x;

                              WidmarkRob wrote:

                              Anyway, you guys have explained to me that the variable y takes on the new value after evaluating the expression.

                              y takes on the new value of y, which is sort of tautological.. One is subtracted from y, that is all.

                              N 1 Reply Last reply
                              0
                              • L Lost User

                                WidmarkRob wrote:

                                int z = y-- + x;

                                WidmarkRob wrote:

                                Anyway, you guys have explained to me that the variable y takes on the new value after evaluating the expression.

                                y takes on the new value of y, which is sort of tautological.. One is subtracted from y, that is all.

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

                                Yes, I get that now… Post-fix decrementing… It takes on the new value after evaluating the expression. On to my new problem. I used this same type of thinking with my so-called simple exercise I was given. y = y++ + x; z = ++z + x; In using that same thought process of y taking on the new value after evaluating the expression, in this new problem (the first expression). I did this in my head before printing it to the console window and came up with 121. The console window printed 111. In trying to keep things in semi-sort of uniform fashion. In my head, I also thought this variable y would take on the new value as well. Where did I go wrong in my head? My Coding Journey

                                L 1 Reply Last reply
                                0
                                • N N8tiv

                                  Yes, I get that now… Post-fix decrementing… It takes on the new value after evaluating the expression. On to my new problem. I used this same type of thinking with my so-called simple exercise I was given. y = y++ + x; z = ++z + x; In using that same thought process of y taking on the new value after evaluating the expression, in this new problem (the first expression). I did this in my head before printing it to the console window and came up with 121. The console window printed 111. In trying to keep things in semi-sort of uniform fashion. In my head, I also thought this variable y would take on the new value as well. Where did I go wrong in my head? My Coding Journey

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

                                  How did you get 121?

                                  N 1 Reply Last reply
                                  0
                                  • L Lost User

                                    How did you get 121?

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

                                    int x = 10; int y = 100; int z = y; Then write a C# program to compute and display the values of the variables y and z after executing these expressions: y = y++ + x; z = ++z + x; This exercise is virtually the same as the example they gave to me in the beginning. (My original question I was asking about) When I print the variable y to the console window, the result is 110. (Which is what I came up but in my head) Using the same thought process as in the example, where this variable y also takes on the new value (110)… I used this new value in my head. This so-called simple exercise is using "Boxing"? (Just throwing in another term that I learned, hopefully using it correctly) the variable z now equals the variable y. (Which in my mind, I thought would equal 110) The second expression. Prefixes incrementing. So I thought, 110+1+10. That's how I came up with 121 in my head. When I went to go print the variable z to the console window, the result was 111. My Coding Journey

                                    OriginalGriffO 1 Reply Last reply
                                    0
                                    • N N8tiv

                                      int x = 10; int y = 100; int z = y; Then write a C# program to compute and display the values of the variables y and z after executing these expressions: y = y++ + x; z = ++z + x; This exercise is virtually the same as the example they gave to me in the beginning. (My original question I was asking about) When I print the variable y to the console window, the result is 110. (Which is what I came up but in my head) Using the same thought process as in the example, where this variable y also takes on the new value (110)… I used this new value in my head. This so-called simple exercise is using "Boxing"? (Just throwing in another term that I learned, hopefully using it correctly) the variable z now equals the variable y. (Which in my mind, I thought would equal 110) The second expression. Prefixes incrementing. So I thought, 110+1+10. That's how I came up with 121 in my head. When I went to go print the variable z to the console window, the result was 111. My Coding Journey

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

                                      It's pretty simple:

                                      int x = 10;
                                      int y = 100;
                                      int z = y;

                                      At the end of this, you have three variables, each with separate values:

                                      x y z
                                      10 100 100

                                      Although "y" and "z" contain the same number, they aren't linked together, so changing one does not change the other. Think of them as three pockets: two in your trousers, and one in your shirt. If you put ten coins in each pocket, they all have the same number. If you then take 5 coins out of your shirt pocket, you still have ten coins in each of your trouser pockets.

                                      y = y++ + x;

                                      Equates to:

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

                                      Which means that "y" ends up holding 110 - as you have seen.

                                      z = ++z + x;

                                      Is the equivalent of:

                                      int z2 = z + 1;
                                      z = z2 + x;

                                      Which is the same as saying:

                                      z = 11 + 100;

                                      Which gives you the answer: 111

                                      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

                                      N 1 Reply Last reply
                                      0
                                      • OriginalGriffO OriginalGriff

                                        It's pretty simple:

                                        int x = 10;
                                        int y = 100;
                                        int z = y;

                                        At the end of this, you have three variables, each with separate values:

                                        x y z
                                        10 100 100

                                        Although "y" and "z" contain the same number, they aren't linked together, so changing one does not change the other. Think of them as three pockets: two in your trousers, and one in your shirt. If you put ten coins in each pocket, they all have the same number. If you then take 5 coins out of your shirt pocket, you still have ten coins in each of your trouser pockets.

                                        y = y++ + x;

                                        Equates to:

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

                                        Which means that "y" ends up holding 110 - as you have seen.

                                        z = ++z + x;

                                        Is the equivalent of:

                                        int z2 = z + 1;
                                        z = z2 + x;

                                        Which is the same as saying:

                                        z = 11 + 100;

                                        Which gives you the answer: 111

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

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

                                        where it confuses me, if you look at the example I posted… The variable y takes on a new value after evaluating the expression. In my head, I was applying that same logic/thinking too my exercise. I also thought, in my exercise… That the variable y would also take on the new value (in this case, 110) after evaluating the first expression. My Coding Journey

                                        OriginalGriffO 1 Reply Last reply
                                        0
                                        • 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

                                          K Offline
                                          K Offline
                                          Kevin Bewley
                                          wrote on last edited by
                                          #41

                                          This line is the important one: int z = y-- + x; it says to the computer, assign y + x into a variable called z. When you've done that knock one off the stored value of y. so, in the line int z = y-- + x; z gets assigned with 100 + 10 (110) then y gets reduced to 99. In the line z = --z + x; The operation goes; knock one off z then assign the sum of z + x to z. ie. take 1 off 110(z) to get 109; THEN assign 109+10 to z. Basically if the ++ or -- is BEFORE the variable name (--y) then the operation is done BEFORE the rest of the line. But, if the ++ or -- is AFTER the variable name, the operation is done AFTER the rest of the line. Simples! :-)

                                          L 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