Can someone explain how the following code works?
static int index = 0;
public static int GetNextIndex()
{
return index++;
}
I assumed that, as the increment operation happens after the return statement, the variable 'index' will never get incremented.
But when tested with C# compiler, I observed that 'index' is getting incremented.
How does a standard compiler handle this scenario?
This is the intermediate language (IL) that the compiler generates (VS2013RC/.NET 4.5.1RC):
.method public hidebysig static int32 GetNextIndex() cil managed
{
.maxstack 8
L_0000: ldsfld int32 ConsoleApplication4.Program::index
L_0005: dup
L_0006: ldc.i4.1
L_0007: add
L_0008: stsfld int32 ConsoleApplication4.Program::index
L_000d: ret
}
So, what does that do? Let's say that index
has the value 6 before calling it.
L_0000: ldsfld int32 ConsoleApplication4.Program::index
loads the value of index
onto the evaluation stack - stack contains 6
.
L_0005: dup
duplicates the value on the top of the stack - stack contains 6, 6
L_0006: ldc.i4.1
loads the value 1
onto the stack - stack contains 6, 6, 1
L_0007: add
adds the top two values on the stack, and places the result back on the stack. stack contains 6, 7
L_0008: stsfld int32 ConsoleApplication4.Program::index
Stores the top value on the stack into index
. index
now equals 7
, stack contains 6
.
L_000d: ret
Takes the top value on the stack (6
) as the return value.
static int index = 0;
public static int GetNextIndex()
{
return index++;
}
is equivalent to:
static int index = 0;
public static int GetNextIndex()
{
int i = index;
index = index + 1;
return i;
}
hence index
is incremented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With