"Invalid code detected" in MSIL or Native code

Does the compiler compile Unreachable Codes to MSIL or Native code at runtime?

+5
source share
3 answers

The question is a bit unclear, but I'll take a picture.

First, Adam's answer is correct, because there is a difference in IL that the compiler emits based on whether the "optimization" switch is on or off. The compiler is much more aggressive in removing unreachable code with an optimization switch.

. -, de jure; , # . -, - ; , # , . , , , , , , .

unreachable de jure, de facto , .

:

int x = 123;
int y = 0;
if (false) Console.WriteLine(1);
if (x * 0 != 0) Console.WriteLine(2);
if (x * y != 0) Console.WriteLine(3);

Console.WriteLines . - ; # , .

-, - , - . , .

, (2), (3). , , , , , .

(3) , y, , y . , , , .

: , , , :

int z;
if (false) z = 123;
Console.WriteLine(z); // Error
if (false) Console.WriteLine(z); // Legal

, z . , ; z , , !

# 2 , . # 2 :

int x = 123;
int z;
if (x * 0 != 0) Console.WriteLine(z);

, de jure Console.WriteLine . # 3.0, .

, ; - .

+13

# . , CIL . , , :

public static int GetAnswer()
{
    return 42;
    Console.WriteLine("Never getting here!");
}

, ( ) CIL. (, nop ):

.method public static int32 GetAnswer() cil managed
{
    .maxstack 1
    .locals init (int32)

            ldc.i4.s 42 // load the constant 42 onto the stack
            stloc.0 // pop that 42 from the stack and store it in a local
            br.s L_000C // jump to the code at L_000C

            ldstr "Never getting here!" // load the string on the stack
            call void [mscorlib]System.Console::WriteLine(string) // call method

    L_000C: ldloc.0 // push that 42 onto the stack from the local
            ret // return, popping the 42 from the stack
}

, , , , , .

, , , , - . CIL :

.method public static int32 GetAnswer() cil managed
{
   .maxstack 1

    ldc.i4.s 42 // load the constant 42 onto the stack
    ret // return, popping the 42 from the stack
}

, .

+3

, , . , , , :

if (false)
 // do something

-, ( , , if, ).

, - , , , , , ( ..)..

0

All Articles