[Solved] I don’t understand how ‘i’ become 4 [closed]


In c# assigning a value to a variable also returns a value. Usually it is the value that is assigned

Here is an assignment, the current time is assigned to the now variable:

DateTime now = DateTime.Now;

This assignment also results in a returned value of the current time. It means you can legally write this:

DateTime now; 
Console.WriteLine(now = DateTime.Now);

Not only will your now variable end up set to the current time, but the value of what was assigned is printed out, so the current time is printed


This is also an assignment:

int i = 2;

And so is this:

++i;

It is short for this:

i = i + 1;

Now because we know assignments return values we know it’s legal to print out assignments:

Console.WriteLine(i = i + 1);

If i was 2, the sum on the right would be evaluated to give 3, then 3 would be assigned into i, and then also 3 is returned so 3 prints out in the console


i++ is more like a special case, where the value that i was BEFORE the assignment is made, is printed out. You can think of i++ as working like:

int i_before = i; //remember it
i = i + 1;
return i_before; //return the old value

So this:

Console.WriteLine(i++);

If i is 3 already, it will be incremented to 4, but 3 is returned and printed

The easy way to remember the difference between i++ and ++i is:

“in i++ the i is before the ++ so the value you get returned is what i was before it was incremented”


If you just use the increment as a statement on its own, it makes no difference which you use:

int i = 2;
i++;
++i;
Console.WriteLine(i); //4

It only matters which you use if you are relying on the “assignment returns a value” behavior


By the time the last line of your code comes around, i is 4 because it has been incremented twice, from 2

0

solved I don’t understand how ‘i’ become 4 [closed]