Jviaches
Jviaches

Reputation: 843

When ++counter occures, what happens in the memory?

Lets suppose i have :

int counter;
++counter;

The question is : what happened in the memory (stack) ? If there is a new variable creates in stack and copy previous variable's value and add then +1 or its using temp variable, add there +1 and then places new value in counter ?

Upvotes: 3

Views: 125

Answers (5)

Mike de Klerk
Mike de Klerk

Reputation: 12328

.Net first compiles to an intermediate language (IL).

The follogin .Net C# code

private void Form1_Load(object sender, EventArgs e)
{
    int i = 0;
    i++;
    int j = 0;
    ++j;
}

Compiles to IL code, viewed in a disassembler:

ldc.i4.0    //ldc = load constant on evaluation stack
stloc.0 //Store on top of the evaluation stack
ldloc.0 //Load a local variable
ldc.i4.1 //ldc = load constant on evaluation stack
add //add
stloc.0 //Store on local evaluation stack

ldc.i4.0 //Load contant 0 on the evaluation stack
stloc.1 //Store this on variable location 1
ldloc.1 //Load variable location 1
ldc.i4.1 //Load constant 1 on evaluation stack
add //Add 
stloc.1 //Store on evaluation stack

You can see that it does not matter in this case. It both compiles the same way. First load the value on the stack, store in the variable. then load value 1 on the stack, then add and save it in the variable.

I am not sure how this will finally compile to CPU instructions.

Upvotes: 1

jags
jags

Reputation: 2070

This is in addition to Jon's answer.

There is one difference when ++ operator is used before the variable and after the variable. Consider below example:

        int[] arr = { 1, 2, 3 };
        int counter = 0;

        Console.WriteLine(arr[counter++]);
        Console.WriteLine(arr[++counter]);

The counter++ will print 1 and ++counter will print 3.

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941585

It depends, but usually nothing happens to memory. One of the most important jobs done by the jitter is to avoid using memory as much as possible. Particularly for local variables like yours. It stores the value of the variable in a CPU register instead. And the ++ operator simply produces an INC machine code instruction to increment the value in the register. Very fast, it takes 0 or 1 cpu cycle. With 0 being common because it can be executed in parallel with another instruction.

See this answer for a list of optimizations performed by the jitter.

Upvotes: 3

Rob Hardy
Rob Hardy

Reputation: 1821

++counter will increment counter and return the new incremented value. counter++ will increment counter and return the value as it was before incrementation.

Upvotes: 0

Jon
Jon

Reputation: 437386

The value of counter is loaded from memory into a CPU register, it is incremented, and then written back to that same memory address. No additional memory is allocated during this process, and it doesn't make a difference if counter lives in the stack or anywhere else.

Upvotes: 7

Related Questions