I found a lot of articles about statics (MSDN, MSDN 2, Stack Overflow, and lot lot more), but I still can't understand why this code returns -1
:
class Program
{
static int value = 0;
static int foo()
{
value = value - 7;
return 1;
}
static void Main(string[] args)
{
value -= foo();
Console.WriteLine(value);
Console.ReadKey();
}
}
Here's what the debugger shows after foo()
has run, but before the result is subtracted from value
:
But one step later, value
is -1
:
I would expect -8
because of the static field which is stored in memory once.
When I changed it to
var x = foo();
value -= x;
it shows -8
How does this work exactly?
This problem is not about static; it's about how the subtraction works.
value -= foo();
can be expanded to value = value - foo()
The compiler will explain it into four steps:
value
onto the stack.foo
and put the result onto the stack.value
field.So the original value of value
field is already loaded. Whatever you change value
in the method foo
, the result of the subtraction won't be affected.
If you change the order to value = - foo() + value
, then the value of value
field will be loaded after foo
is called. The result is -8
; that's what you are expected to get.
Thanks for Eliahu's comment.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments