Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to assign a value to an int in C# when defaults to 0?

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?

like image 213
John B Avatar asked Sep 14 '09 19:09

John B


People also ask

Why do we use int in C?

An int variable contains only whole numbers Int, short for "integer," is a fundamental variable type built into the compiler and used to define numeric variables holding whole numbers. Other data types include float and double. C, C++, C# and many other programming languages recognize int as a data type.

Why is variable declaration required C?

Variable Declaration in C A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable.

Can we assign value to int?

You can define a variable as an integer and assign a value to it in a single declaration. For example: int age = 10; In this example, the variable named age would be defined as an integer and assigned the value of 10.

Why assign variables to data types?

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.


4 Answers

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.

like image 193
Marc Gravell Avatar answered Oct 01 '22 04:10

Marc Gravell


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.

like image 45
ChrisW Avatar answered Oct 01 '22 04:10

ChrisW


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.

like image 23
Martin Harris Avatar answered Oct 01 '22 03:10

Martin Harris


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
   }
}
like image 33
shahkalpesh Avatar answered Oct 01 '22 03:10

shahkalpesh