Why is incrementing an integer in C # executed after the function returns its value?

Why do two functions return different values?

When I call this function, passing 0 as a parameter, it returns 1

    public static int IncrementByOne(int number)
    {
        return (number + 1);
    }

However, when I call this function, passing 0 as a parameter, it returns 0, even if the increment is performed, and the numeric variable changes its value to 1 inside the method?

    public static int IncrementByOne(int number)
    {
        return number++;
    }

What is the reason that the return values ​​of these two functions are different?

+4
source share
4 answers

number++ - . , . , , preincrement ++number

. : https://msdn.microsoft.com/en-us/library/36x43w8w.aspx

+10

- () ++ operator - . , 2, 2, 3, .

public static int IncrementByOne(int number)
{
    return number++;
}

IL, , :

IncrementByOne:
    IL_0000:  ldarg.0        // load 'number' onto stack
    IL_0001:  dup            // copy number - this is the reason for the
                             // postfix ++ behavior
    IL_0002:  ldc.i4.1       // load '1' onto stack
    IL_0003:  add            // add the values on top of stack (number+1)
    IL_0004:  starg.s     00 // remove result from stack and put
                             // back into 'number'
    IL_0006:  ret            // return top of stack (which is
                             // original value of `number`)

, postfix ++ ( ) - dup - number , ret statment , . number.

+3

The last function adds a number; If an immediate increase is required, you can tryreturn ++number;

0
source

Or, to indicate the approach of a caveman ...

public static int IncrementByOne(int number)
{
    number++;
    return number;
}
0
source

Source: https://habr.com/ru/post/1654135/


All Articles