How does the compiler handle the return statement using the postfix statement?

Can someone explain how the following code works?

static int index = 0;
public static int GetNextIndex()
{
    return index++;
}

I suggested that since the increment operation occurs after the return statement, the variable 'index' will never increase.

But when testing with the C # compiler, I noticed that the index "index" gets an increment.

How does a standard script handle this script?

+4
source share
2 answers

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 this do? Let's say that indexit matters 6 before calling it.

    L_0000: ldsfld int32 ConsoleApplication4.Program::index

index - 6.

    L_0005: dup

- 6, 6

    L_0006: ldc.i4.1

1 - 6, 6, 1

    L_0007: add 

. 6, 7

    L_0008: stsfld int32 ConsoleApplication4.Program::index

index. index 7, 6.

    L_000d: ret 

(6).

+6
static int index = 0;
public static int GetNextIndex()
{
    return index++;
}

:

static int index = 0;
public static int GetNextIndex()
{
    int i = index;
    index = index + 1;
    return i;
}

, index .

+6

All Articles