views:

132

answers:

4

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?

+3  A: 

It depends on the condition of the if. For example if you are checking a reference against null the compiler will emit a brfalse instruction (or a brtrue depending on what you wrote).

The actual if condition will differ based on the condition itself but a dissasembler like ILDASM or Reflector would be a better tool for learning more.

Andrew Hare
A: 

A simple example:

ldloc.1                    // loads first local variable to stack
ldc.i4.0                   // loads constant 0 to stack
beq                        // branch if equal

This would be equal to

if(i == 0) //if i is the first local variable

Other ifs would differ, including conditional branches. This really is too much to explain in one post, you are better of looking for an introduction to IL-Code.

There is a nice article on codeproject concerning this.

Femaref
`ldloc.1` loads the second local variable. ☺ Also, in your example `if` translates to `beq`, not `ceq`.
Timwi
ldloc.0 usually is the local class. you are right with beq of course.
Femaref
+4  A: 

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

Timwi
+2  A: 

A branch instruction is used that will jump to a target instruction depending on the value(s) on top of the stack.

brfalse Branch to target if value is zero (false)
brtrue  Branch to target if value is non-zero (true)
beq     Branch to target if equal
bge     Branch to target if greater than or equal to
bgt     Branch to target if greater than
ble     Branch to target if less than or equal to
blt     Branch to target if less than
bne.un  Branch to target if unequal or unordered
Mark Cidade