Skip to content

Improve code generation for switch statements #233

@adrianoc

Description

@adrianoc

There are at least 2 potential improvements:

  • Better naming variables used to store the instructions representing the start of code for each case, i.e, instead of naming them Nop_[number], use something like CaseCode_[index]_[number] or Case_[index]_[number] or similar. This improves code readability

  • If there is a default case, do not emit unreachable code (See code below).

class Foo
{
    void Bar(int j)
    {
        switch(j)
        {
            case 1: System.Console.WriteLine(1); break;
            case 2: System.Console.WriteLine(2); break;
            default: System.Console.WriteLine(3); break;
        }
    }
}
//case 2: (condition)
il_Bar_2.Emit(OpCodes.Ldloc, lv_switchCondition_4);
il_Bar_2.Emit(OpCodes.Ldc_I4, 2);
il_Bar_2.Emit(OpCodes.Beq_S, Nop_7);

// Jumps to the *default* handling
il_Bar_2.Emit(OpCodes.Br, Nop_8); 

// Unreachable code jumping to the end of the switch. If there's a `default` case, this should not be emitted.
il_Bar_2.Emit(OpCodes.Br, Nop_5);

Metadata

Metadata

Assignees

No one assigned

    Labels

    💗 good first featurea feature that is relatively easy to implementenhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions