Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No "Unassigned Local Variable" error?

Tags:

c#

.net

c#-3.0

Why does taking the address of a variable eliminate the "Use of unassigned local variable" error?

(Why can we take the address without initialization in the first place?)

static unsafe void Main()
{
    int x;
    int* p = &x;  //No error?!
    x += 2;       //No error?!
}
like image 542
user541686 Avatar asked May 19 '11 06:05

user541686


2 Answers

C# Language spec, section 18.5.4:

The & operator does not require its argument to be definitely assigned, but following an & operation, the variable to which the operator is applied is considered definitely assigned in the execution path in which the operation occurs. It is the responsibility of the programmer to ensure that correct initialization of the variable actually does take place in this situation.
...
The rules of definite assignment for the & operator exist such that redundant initialization of local variables can be avoided. For example, many external APIs take a pointer to a structure which is filled in by the API. Calls to such APIs typically pass the address of a local struct variable, and without the rule, redundant initialization of the struct variable would be required.

like image 147
Gabe Avatar answered Nov 08 '22 21:11

Gabe


I think because, once you've taken a pointer to the variable, there's no way for the compiler to analyze whether a value is assigned via that pointer, so it's excluded from the definite assignment analysis.

like image 2
Damien_The_Unbeliever Avatar answered Nov 08 '22 20:11

Damien_The_Unbeliever