How to remove compiler error with struct: “Use of unassigned local variable”

前端 未结 2 960
天涯浪人
天涯浪人 2020-12-12 06:05

The C# compiler is a bit ... old fashioned ... and won\'t do static analysis. So it breaks on seemingly correct code like this:

MyStruct s;
bool ini         


        
2条回答
  •  温柔的废话
    2020-12-12 06:37

    The C# specification was designed such that you should never be able to use an uninitialized variable. This is not an old fashioned concept. The old fashioned way to deal with this (in C++) was to say, "This is undefined behaviour, anything can happen".

    Strangely enough lots of bugs were caused by this attitude, which gave rise to many compilers automagically initing (in debug mode) variables into such gems as 0xDEADBEEF.

    As for why the C# compiler doesn't do code analysis to find if the variable is inited when it reaches that code?

    Halting Problem

    The problem could be rewritten like this.

    bool inited = false;
    MyStruct? s;    
    
    while (true)
    {
       foreach( Something foo in ACollection )
          foo.Test();
       if( inited && false == s.HasValue )
          return;
    }
    

    This is only slightly changed code. But you can see, I have converted your problem into the Halting Problem, where the inputs are, the state of each Something and the implementation of foo.Test().

    This is proven to be undecidable on a Turing Machine, which your CLR VM certainly is.

    In short, you are asking, why hasn't microsoft broken the laws of Mathematics and Computer Science when they wrote the C# compiler.

    Or you are asking, shouldn't the Microsoft C# Compiler try hard before giving up on the Halting Problem. To which my response is, how hard should they try?

提交回复
热议问题