Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does an if look like in IL?

What does an if statement look like when it's compiled into IL?

It's a very simple construct in C#. Can sombody give me a more abstract definition of what it really is?

like image 399
DaveDev Avatar asked Nov 29 '22 05:11

DaveDev


1 Answers

Here are a few if statements and how they translate to IL:

ldc.i4.s 0x2f                      var i = 47;
stloc.0 

ldloc.0                            if (i == 47)
ldc.i4.s 0x2f
bne.un.s L_0012

ldstr "forty-seven!"                   Console.WriteLine("forty-seven!");
call Console::WriteLine

L_0012:
ldloc.0                            if (i > 0)
ldc.i4.0 
ble.s L_0020

ldstr "greater than zero!"             Console.WriteLine("greater than zero!");
call Console::WriteLine

L_0020:
ldloc.0                            bool b = (i != 0);
ldc.i4.0 
ceq 
ldc.i4.0 
ceq 
stloc.1 

ldloc.1                            if (b)
brfalse.s L_0035

ldstr "boolean true!"                  Console.WriteLine("boolean true!");
call Console::WriteLine

L_0035:
ret

One thing to note here: The IL instructions are always the “opposite”. if (i > 0) translates to something that effectively means “if i <= 0, then jump over the body of the if block”.

like image 176
Timwi Avatar answered Dec 16 '22 15:12

Timwi