Why are local variables definitely assigned in unreachable statements?

Why are local variables definitely assigned in unreachable statements?

Rate This
  • Comments 24

You're probably all familiar with the feature of C# which disallows reading from a local variable before it has been "definitely assigned":

void M()
{
  int x;
  if (Q())
    x = 123;
  if (R())
    Console.WriteLine(x); // illegal!
}

This is illegal because there is a path through the code which, if taken, results in the local variable being read from before it has been assigned; in this case, if Q() returns false and R() returns true.

The reason why we want to make this illegal is not, as many people believe, because the local variable is going to be initialized to garbage and we want to protect you from garbage. We do in fact automatically initialize locals to their default values. (Though the C and C++ programming languages do not, and will cheerfully allow you to read garbage from an uninitialized local.) Rather, it is because the existence of such a code path is probably a bug, and we want to throw you in the pit of quality; you should have to work hard to write that bug.

The way in which the compiler determines if there is any path through the code which causes x to be read before it is written is quite interesting, but that's a subject for another day. The question I want to consider today is: why are local variables considered to be definitely assigned inside unreachable statements?

void M()
{
  int x;
  if (Q())
    x = 123;
  if (false)
    Console.WriteLine(x); // legal!
}

First off, obviously the way I've described the feature immediately gives the intuition that this ought to be legal. Clearly there is no path through the code which results in the local variable being read before it is assigned. In fact, there is no path through the code that results in the local variable being read, period!

On the other hand: that code looks wrong. We do not allow syntax errors, or overload resolution errors, or convertibility errors, or any other kind of error, in an unreachable statement, so why should we allow definite assignment errors?

It's a subtle point, I admit. Here's the thing. You have to ask yourself "why is there unreachable code in the method in the first place?" Either that unreachable code is deliberate, or it is an error.

If it is an error, then something is deeply messed up here. The programmer did not intend the written control flow in the first place. It seems premature to guess at what the definite assignment errors are in the unreachable code, since the control flow that would be used to determine definite assignment state is wrong. We are going to give a warning about the unreachable code; the user can then notice the warning and fix the control flow. Once it is fixed, then we can consider whether there are definite assignment problems with the fixed control flow.

Now, why on earth would someone deliberately make unreachable code? It does in fact happen; actually it happens quite frequently when dealing with libraries made by another team that are not quite done yet:

// If we can resrov the frob into a glob, do that and then blorg the result.
// Even if the frob is not a glob, we know it is definitely a resrovable blob,
// so resrov it as a blob and then blorg the result. Finally, fribble
// the blorgable result, regardless of whether it was a glob or a blob.
void BlorgFrob(Frob frob)
{
  IBlorgable blorgable;
  // TODO: Glob.TryResrov has not been ported to C# yet.
  if (false /* Glob.TryResrov(out blorgable, frob) */)
  {
    BlorgGlob(blorgable);
  }
  else
  {
    blorgable = Blob.Resrov(frob)
    BlorgBlob(blorgable);
  }
  blorgable.Fribble(frob);
}

Should BlorgGlob(blorgable) be an error? It seems plausible that it should not be an error; after all, it's never going to read the local. But it is still nice that we get overload resolution errors reported inside the unreachable code, just in case there is something wrong there.

  • @Vlad

    I believe you need to set the Initialize locals flag to get verifiable code. This is a CLR level rule, whereas the definitely assigned stuff is a C# level rule. In many, but not all cases the just-in-time compiler will optimize out the unnecessary initialization.

  • @ChristianBjerre: Your unreachable code doesn't try to access any not-definitely-assigned variables, so there is no warning. (Or are you asking why the compiler isn't more aggressive with its unreachable code analysis? Think generics.)

  • Adding lots of static analysis to future VS editions can only help produce better code.  For example, flagging local variables as 'Local variable X could be moved to inner scope' would be great.

  • BTW I'd like to express how much I love the definite assignment requirement. It makes it very easy to verify that all code paths are assigning to a variable, like in a complex if/then/else/switch. All I do is not assign when I declare, and let the compiler tell me I'm okay. This is also fantastic for later maintenance, because the compiler will yell at you if you made a change that is almost certainly unintentional.

  • @Raymond Chen: Yes, Raymond. That's my question. It's on the unreachable code analysis that I'm on to - spawned from Eric's article. A more aggressive code analysis will improve lots of code.

  • @Christian Bjerre; Please remember that the unreachability-analysis has to be easily and precisely describable and implementable, because it's part of the standard. If you have a different analyzer following different rules for each implementation, you can never change the implementation without risking introducing new errors/warnings. BTW, that includes Microsoft enhancing their compiler for the next better version. Or you might be forced to downgrade. Ever worked on a second pc?

  • @Deduplicator: This case is described in section "8.1 End points and reachability" of the standard. The same example is used as I did (didn't check before I wrote my example). The ability to analyse the code and point to code which is wrong according to a set of rules (that can extent the standard) is an important feature when you write code. Today we only have the Microsoft C# compiler to do this for us. Previously we has a set of C/C++ compilers implementing the same standard, but extending the code analysis with their own set of rules. We used this extensive back then and got better code as some rules were added as compiler specific warnings, but were warning about general problems with the code. Any changes to the specific compiler did cause some work, but in all cases increasing code quality. I'm not sure I understand your comment about the "second PC".

  • Why can't we re-use or re-declare a variable previously defined in a child scope, for/foreach loop, etc.?!

    for (int i = 0; i < 5; i++)

    {

    }

    int i = 1; // no!

    i++; // no!!

  • "We do in fact automatically initialize locals to their default values."

    Except when two distinct variables are merged into one by the compiler. The CLR only initializes that single variable once. The second C# variable will start with the value last found in the first C# variable.

Page 2 of 2 (24 items) 12