The following code written in C# in VS2010 for .Net 4.0:
bool b = false;
has the following disassembly:
XOR EDX,EDX
MOV DWORD PTR[EBP-3Ch],EDX
which makes perfect sense.
However, the following code:
bool b = true;
has the following disassembly:
MOV EAX,1
AND EAX,0FFh
MOV DWORD PTR[EBP-3Ch],EAX
What is the purpose of the AND
operation? Why not just MOV EAX,1
?
Line | EAX
-----------
1 | 0x01
2 | 0x01 & 0xFF = 0x01
3 | 0xFF
The default value of the bool type is false .
One of them is ' bool . ' The ' bool ' type can store only two values: true or false . To create a variable of type bool, do the same thing you did with int or string . First write the type name, ' bool ,' then the variable name and then, probably, the initial value of the variable.
(You might know that the default value of a bool variable is false).
The default value of Boolean is False . Boolean values are not stored as numbers, and the stored values are not intended to be equivalent to numbers. You should never write code that relies on equivalent numeric values for True and False .
I suspect the and 0xff
is truncation to 8-bit bool. I don't know nearly enough about the internals to be sure, but I suspect bool b = true
is becoming something like bool b = int(1)
which is then becoming bool b = bool(int(1))
and it's that coercion to bool causes the and 0xff
. I see similar things in x86 epilogs of C++ functions returning bool (e.g. ending in test; setal
) rather than just returning an arbitrary nonzero value.
This is the kind of code that a peephole optimizer would fix...
This code
bool a = true;
bool c = false;
generates this IL assembly:
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.0
IL_0004: stloc.1
You can see in the intermediate language, the code is essentially the same. How the jitter is translating that, or why it would not do effectively parallel code for the two is very bizarre.
(I put this as an answer instead of a comment just so I could format the discussion to be readable.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With