croses initialization of "XXX"

2008年11月30日星期日

 

"The compiler objects to my declaring a variable in one of the
branches of a case statement. Earlier versions used to accept this
code. Why?"

The draft standard does not allow a goto or a jump to a case label to
skip over an initialization of a variable or a class object. For
example:

switch ( i ) {
case 1:
Object obj(0);
...
break;
case 2:
...
break;
}

The reason is that `obj' is also in scope in the rest of the switch
statement.

As of version 2.7.0, the compiler will object that the jump to the
second case level crosses the initialization of `obj'. Older compiler
versions would object only if class Object has a destructor. In either
case, the solution is to add a set of curly braces around the case
branch:

case 1:
{
Object obj(0);
...
break;
}

2.7版本以后的编译器,反对直接跳到第二个case语句,而省略了第一个case语句中的初始化。
而且这样的语句的结果是,obj在以后的case里依然有效,所以报错。
最好的就是,加个{},就是局部作用域了:)

0 评论: