Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interesting interview exercise result: return, post increment and ref behavior [duplicate]

Here's a simple console application code, which returns a result I do not understand completely.

Try to think whether it outputs 0, 1 or 2 in console:

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main()
        {
            int i = 0;
            i += Increment(ref i);

            Console.WriteLine(i);
            Console.ReadLine();
        }

        static private int Increment(ref int i)
        {
            return i++;
        }
    }
}

The answer is 0.

What I don't understand is why post increment i++, from the Increment method, which is executed on a ref (not on a copy of the passed variable) does increment the variable, but it just gets ignored later.

What I mean is in this video:

Can somebody explain this example and why during debug I see that value is incremented to 1, but then it goes back to 0?

like image 775
Aremyst Avatar asked Apr 21 '17 10:04

Aremyst


2 Answers

i += Increment(ref i); is equivalent to

i = i + Increment(ref i);

The expression on the right hand side of the assignment is evaluated from left to right, so the next step is

i = 0 + Increment(ref i);

return i++ returns the current value of i (which is 0), then increments i

i = 0 + 0;

Before the assignment the value of i is 1 (incremented in the Increment method), but the assignment makes it 0 again.

like image 132
Jakub Lortz Avatar answered Nov 09 '22 01:11

Jakub Lortz


i think the "magic" here is just operation precedence the order of operations

i += Increment(ref i)

is the same as

i = i + Increment(ref i)

the + operation is executed left to right

so first we take i ... wich is 0 at that time ...

then we add the result of Increment(ref i) ... which is also 0 ... 0+0=0 ... but wait ... before we get that result i is actually incremented ...

that increment takes place after the left operand of our + operation has ben evaluated ... so it does not change a thing ... 0+0 still is 0 ... thus i is assigned 0 after the + operation has been executed

like image 18
DarkSquirrel42 Avatar answered Nov 08 '22 23:11

DarkSquirrel42