3

I've found a really cool feature of a compilator. However, I cannot understand logic of this behaviour.

static int IncrementValue(ref int i) { return i++;}

and Main method:

static void Main(string[] args)
{
    int a = 2;
    int b = IncrementValue(ref a);
    Console.WriteLine(a+b);
} 

The output is 5.

My question is:

  1. Why is "b" field equal 2? (In my view, it ought to be 3 as "ref" keyword is not copying by value, but the keyword takes field by value. Consequently, "b" should be as "a+1")
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
StepUp
  • 36,391
  • 15
  • 88
  • 148
  • 4
    You are aware that the *return value* of `i++` is the *non-incremented value*? Maybe you meant to write `return ++i;`? – Heinzi Mar 12 '15 at 07:53
  • This is not a "cool feature". __`++`__ is obscure, as you have found out. – H H Mar 12 '15 at 07:57
  • 2
    For some strange reason people use i++ more often than ++i, where ++i is in many case more correct and leads to less errors. – Philip Stuyck Mar 12 '15 at 07:57

2 Answers2

5

Since you wrote it as;

return i++

This will still return 2 as a value but it will increase a value to 3 after the expression.

If you wrote it as;

return ++i

This will return incremented value which is 3, and since a will be 3 after the execute it, it will be printed 6 as a result.

Further reading

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • Not really *after it returns*, but after the expression has determined its value. Basically the statement will be executed as follows: Read the current value of `i`, then increment `i`, then return the value we read before we incremented it. Returning is still the last thing that is done in that method. – Lasse V. Karlsen Mar 12 '15 at 14:17
  • @LasseV.Karlsen Yes, _after the expression_ is much clear explanation. Since English is not my mother language, sometimes I can't express myself properly. – Soner Gönül Mar 12 '15 at 14:45
1

i++ is the post increment operator. It will increment the value afterwards, instead of before the value is returned.

Change i++ to ++i to make it increment before the value is returned, or increment the value in a separate statement and then return the value:

static int IncrementValue(ref int i) { return ++i; }

Or:

static int IncrementValue(ref int i) { i++; return i; }

(The reason you see different values when returning the integer, is that the result is copied. It is not a reference, else the return statement would not be useful at all).

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325