0

I dont understand why the value of i and k is still 5 in line number 19 ,20,after post increment?

The value of i is still 5 though after post increment.

`using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Increment
{
class Program
    {
        static void Main(string[] args)
        {
            int i = 5;
            int j = 10;
            Console.WriteLine("before incrementing{0}",i);    
             i=i++;    
            Console.WriteLine("after incrementing {0}",i);   //i=5? 
             int k = i;    
    Console.WriteLine("after incrementing i and assign {0}", k);//K=5?
}
    }
}`
  • Is this just experimentation to see what happens, or an example of a bug? If a bug, just use `i++` instead of `i=i++`. If experimentation then Andrews answer below covers it better than I would have :p. – Ben May 08 '19 at 02:59
  • You can just write `++i;`. – Jimi May 08 '19 at 03:00
  • 1
    [What is the difference between i++ and ++i](https://stackoverflow.com/a/3346729/7444103) – Jimi May 08 '19 at 03:06

2 Answers2

5

Imagine post-increment and pre-increment as functions:

 int PreIncrement(ref int i)
 {
     i = i + 1;
     return i;
 }

 int PostIncrement(ref int i)
 {
     int valueBefore = i;
     i = i + 1;
     return valueBefore;
 }

In this case

i = i++;

would be the equivalent of

i = PostIncrement(ref i);

You are performing two actions, in this order:

  • Incrementing i
  • Setting i to equal the value it equalled before it was incremented
Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205
  • I think the actual reason is https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#simple-assignment (right side evaluated completely before assignment), but this explanation is visual enough to see why it happens. – Alexei Levenkov May 08 '19 at 04:57
0

The documentation for ++ has reasonably clear examples. "The result of x++ is the value of x before the operation, as the following example shows... ."

That means however you use x++ in an expression you will be getting the initial value, i.e. prior to x being incremented. So if x is 4 then the value 4 will be used in the expression and x will be incremented to 5. If the expression's value is assigned to a variable then the variable is set to 4. You happen to have chosen x as the target of the assignment, thus overwriting the post-incremented value.

HABO
  • 15,314
  • 5
  • 39
  • 57