Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net assembly adds superfluous AND when setting bool to TRUE?

Tags:

c#

assembly

clr

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
like image 350
Ozzah Avatar asked Nov 23 '12 03:11

Ozzah


People also ask

Is bool automatically false?

The default value of the bool type is false .

How can set boolean value to true in C#?

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.

Is bool true by default C#?

(You might know that the default value of a bool variable is false).

Does bool default to 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 .


2 Answers

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...

like image 186
Ben Jackson Avatar answered Nov 15 '22 08:11

Ben Jackson


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.)

like image 43
SAJ14SAJ Avatar answered Nov 15 '22 10:11

SAJ14SAJ