Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this code unreachable?

I found a case where I have some code that I believe to be unreachable and is not detected. No warning is issued neither by the compiler nor by Visual Studio.

Consider this code:

enum Foo { A, B, C } class Bar { public Foo type; }  static class Program {     private static void Main()     {         var bar = new Bar { type = Foo.A };          if (bar.type == Foo.B)         {             Console.WriteLine("lol");         }     } } 

Obviously, the program will not print out "lol" because the condition in the if statement is false. I do not understand why a warning is not issued for the unreachable code though. My only hypothesis is that that could potentially be reachable if you have a race condition in a multi-threaded program. Is this correct?

like image 756
Michele Ippolito Avatar asked Apr 13 '18 08:04

Michele Ippolito


People also ask

Why does it say my code is unreachable?

In computer programming, unreachable code is part of the source code of a program which can never be executed because there exists no control flow path to the code from the rest of the program.

How do I fix unreachable code in C++?

Just add a premature return while working on the code in the function or the code calling the function.

How do you find an unreachable code?

While some simple cases of unreachable code can be detected by static analysis (typically if a condition in an if statement can be determined to be always true or false), most cases of unreachable code can only be detected by performing coverage analysis in testing, with the caveat that code reported as not being ...


1 Answers

Static analysis can only do so much, and it will only mark code as unreachable if it can prove that a value cannot be changed. In your code, what happens inside Bar is out of the scope of the method flow and can't be statically reasoned about. What if Bar's constructor launches a thread that sets the value of type back to B? The compiler can't know about it, because, again, the internals of Bar aren't scoped to the method.

If your code was checking the value of a local variable, then the compiler could know if there was no way for it to change. But that's not the case here.

like image 107
Avner Shahar-Kashtan Avatar answered Oct 15 '22 18:10

Avner Shahar-Kashtan