为什么本地变量必须有初始值 [英] Why must local variables have initial values
问题描述
为什么一定要我初始化变量里面的方法呢?
INT test1的; //未初始化,但确定公众诠释美孚()
{
INT TEST2; //未初始化 INT TEST3 = test1的; // 好
INT TEST4 = test2的; // 一个错误
}
字段自动初始化为类型的逻辑为零;这是隐含的。变量必须遵守明确赋值,所以必须它们可以被读取之前进行分配。
ECMA 334v4
§17.4.4字段初始化
字段的初始值,是否
它是一个静态字段或实例
场,是默认值(§12.2)
该字段的类型。这不可能
之前以观察字段的值
此默认初始化
发生,并且一个场是因而从未
未初始化。
块引用>和
§12。变量
...
变量应前明确赋值(§12.3)的
能够得到的值。
...
块引用>Why must I initialize variables inside methods?
int test1; // Not initialized, but ok public int Foo() { int test2; // Not initialized int test3 = test1; // Ok int test4 = test2; // An error }
解决方案Fields are automatically initialized to the logical zero for the type; this is implicit. Variables must obey "definite assignment", so must be assigned before they can be read.
ECMA 334v4
§17.4.4 Field initialization
The initial value of a field, whether it be a static field or an instance field, is the default value (§12.2) of the field’s type. It is not possible to observe the value of a field before this default initialization has occurred, and a field is thus never "uninitialized".
and
§12. Variables
... A variable shall be definitely assigned (§12.3) before its value can be obtained. ...
这篇关于为什么本地变量必须有初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!