Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does compiler handle return statement with postfix operator?

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?

like image 806
Arctic Avatar asked Dec 16 '22 05:12

Arctic


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 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.

like image 188
Damien_The_Unbeliever Avatar answered Dec 21 '22 22:12

Damien_The_Unbeliever


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.

like image 26
Ahmed KRAIEM Avatar answered Dec 22 '22 00:12

Ahmed KRAIEM