IL bne Instruction

Collection abstraction

If-statements are translated into branch instructions. One such intermediate language instruction, bne, stands for branch if not equal. We see an example of its use by a compiled C# program here.

If Statement

Example

The important method here is called A(). If its argument is equal to 1, it writes something to the console; if the argument is not equal to 1, it writes something else. Its argument is pushed to the evaluation stack with ldarg. The constant 1 is pushed to the stack with ldc.

ldarg Instruction ldc InstructionSteps

Then, the bne instruction is used. If the two values on the top of the evaluation stack (the constant 1 and the argument int) are not equal, we jump forward to line IL_000f. This means if the argument is 1, we do not jump and instead go the next instruction (where we print "Hi"). Please notice how the ret instruction is used so the program ends.

ret Instruction

This .NET IL example shows the bne instruction and the original C# program.

Program that uses bne instruction [C#]

using System;

class Program
{
    static void Main()
    {
	A(0);
	A(1);
	A(2);
    }

    static void A(int value)
    {
	if (value == 1)
	{
	    Console.WriteLine("Hi");
	}
	else
	{
	    Console.WriteLine("Bye");
	}
    }
}

Output

Bye
Hi
Bye

A() method [IL]

.method private hidebysig static void  A(int32 'value') cil managed
{
  // Code size       26 (0x1a)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldc.i4.1
  IL_0002:  bne.un.s   IL_000f
  IL_0004:  ldstr      "Hi"
  IL_0009:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000e:  ret
  IL_000f:  ldstr      "Bye"
  IL_0014:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0019:  ret
} // end of method Program::A

Summary

Branch instructions such as bne (branch if not equal) translate conditional statements such as if/else into flat sequences of instructions. This is done by doing a simple integer comparison of the top two values of the evaluation stack and then jumping forward to another position in the program based on the result.

Intermediate Language
.NET