[英]No “Unassigned Local Variable” error?
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?!
}
C# Language spec, section 18.5.4: C#语言规范,第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.
例如,许多外部API采用指向由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.
对此类API的调用通常会传递本地struct变量的地址,如果没有该规则,则需要对struct变量进行冗余初始化。
我想因为,一旦你指向变量,编译器就无法分析是否通过该指针赋值,因此它被排除在明确的赋值分析之外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.