Question

This works:

class MyClass
{
    int a;

    public MyClass()
    {
        int b = a;
    }
}

But this gives a compiler error ("Use of unassigned local variable 'a'"):

class MyClass
{
    public MyClass()
    {
        int a;
        int b = a;
    }
}

As far as I can tell this happens because in the first example, technically, the compiler doesn't know that 'a' is not assigned. In the latter example, 'a' is defined locally, and therefore is easy to track.

But why does the latter example not work?

Don't integers default to 0? Is this something the compiler enforces for "best practices". Or is there another reason?

Was it helpful?

Solution

In the first example it is a field. Fields automatically default to 0/false/null. In the second example it is a variable. Variables are not defaulted, and must have "definite assignment" before they are used.

Essentially, when creating an object (or initializing a struct) it zeros the memory (or in the case of a non-default struct ctor, forces you to manually initialize everything). However, variables are so common (in every method) that it doesn't want the overhead of having to zero the stack all the time. It instead forces you to indicate the initial value.

OTHER TIPS

Don't integers default to 0?

They do when they're data members of a class, but not when they're a local variable: local variables need to be initialized explicitly before they're used, hence the compiler error.

When you instantiate a new instance of a class all the memory that the object needs is "zeroed" ints are set to 0 strings are set to null etc. This is to avoid a lot of the weird memory bugs and hacks that were possible in C(++). Unfortunately this also has a small processing cost, so when you create a local variable the language assumes is that you will set the value yourself very soon and doesn't bother zeroing it to decrease the total number of required instructions. To offset the risk of using unset memory this introduces the compiler checks to ensure that a value has been set before it will allow you to use the variable.

That could be because variable declared at class level cannot be assigned value at the same scope (other than when declaring)

e.g

class Test
{
   int a;

   a = 0; // this is not allowed at class level & hence a initialized to default
}

whereas

class Test
{
   void test()
   {
     int a;
     int b = a;

     a = 20; // this is allowed
   }
}

As per my knowledge when we declare a variable in class and created an object then the default constructor initializes the variable and so there is no need for initializing the class variables. But coming to the methods in class there is no constructor or anything to initialize those variables so we cannot assign uninitialized variables in the methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top