Gusto
Gusto

Reputation: 1513

What is the value of un-assigned variable (null VS 0)

I was doing an assignment where I should find some errors. The code is as follows:

int num, num2;            
num = Convert.ToInt32(Console.ReadLine());
int answer = num + num2;

My answer was that the num2 should be assigned a value before it can be used and that its value is "null" for the moment. The teacher said that this is wrong answer and the value of num2 is 0. Who is right and why? If the value of num2 were really 0 (by default), I could be able to manipulate it then (do some math etc), but I can't since there is en error, so it means that it cannot be 0! So, what is the value of num2?

Upvotes: 1

Views: 75

Answers (4)

David
David

Reputation: 218877

You're both wrong.

My answer was that the num2 should be assigned a value before it can be used and that its value is "null" for the moment.

Your first part was correct, but your second part was incorrect. An int can never be null. The default value for an int is 0. However, since the variable is never assigned a value in the first place (not even its default) then the compiler itself won't allow the code to compile.

Since the code never compiles, it never runs. And since it never runs, no variable ever has any value.

The teacher said that this is wrong answer and the value of num2 is 0.

The teacher overlooked the fact that the code doesn't compile in the first place. A default value for an int would be 0, in the case of something like a class property:

class MyClass
{
    public int SomeInt { get; set; }
}

In any constructed instance of MyClass, SomeInt would have the value of 0. But for a locally declared variable, the compiler requires that the variable be assigned a value. The code provided doesn't pass that requirement.

Upvotes: 4

Flat Eric
Flat Eric

Reputation: 8111

None is right, neither you nore your teacher, since num2 is a local variable, it cannot be used until initialized. You would get a compiler error "Use of unassigned local variable"

If it would be a field, then its default value would be 0. It can never be null because it is a value type.

Upvotes: 6

Sebastiaan Peters
Sebastiaan Peters

Reputation: 34

int is an value type, so it can't be null.

Upvotes: 0

NikolaiDante
NikolaiDante

Reputation: 18639

An int isn't nullable, so it has a default value which is indeed zero.

You can see the value by calling default(int).

There is a table on msdn of all default values.

Upvotes: 2

Related Questions