我怎样才能从定义中分离出int数组的声明?对不起基本问题.我基本上来自c/c ++背景.
int [] res;
switch (something)
{
case <something>:
res = somefunction ()
break;
{
if ( res == null ) ==>> problem is here. // 'res' might not have been initialized.
Run Code Online (Sandbox Code Playgroud)
我该如何处理这个问题,最好的方法是什么?
正如提到的其他答案,你可以做到
int [] res = null;
Run Code Online (Sandbox Code Playgroud)
但我经常更喜欢确保switch处理所有情况:
int [] res; // Leave it uninitialized
// ...
switch (something) // Set `res` in every branch
{
case <something>:
res = somefunction();
break;
// ...
default: // Including the default
res = null;
break;
}
Run Code Online (Sandbox Code Playgroud)
这样,如果你添加一个新条件,你必须有意识地决定你应该做什么res(因为如果你什么都不做,编译器会提醒你).
pre-init和"处理所有路径"方法都有用例.
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |