当我case在C++中的代码块周围使用大括号来本地化变量时,我应该放在break块的内部还是外部?
case FOO: // 'break' inside
{
int i;
doStuff();
break;
}
case BAR: // 'break' outside
{
int i;
doStuff();
}
break;
Run Code Online (Sandbox Code Playgroud)
谢谢.
它应该出现在.
例如:
switch(value)
{
case 0:
{
// this ...
// that ...
// and the other ...
}
break;
}
Run Code Online (Sandbox Code Playgroud)
编辑文本如下
这主要是为了提高可读性和可维护性,这是一个例子.
switch (value)
{
case 0:
// Do this...
// Do that...
break;
case 1:
//and the other...
break;
}
Run Code Online (Sandbox Code Playgroud)
和
switch (value)
{
case 0:
// Do this...
// Do that...
if (ObjectWithinScope.Type == Fault)
break;
case 1:
//and the other...
break;
}
Run Code Online (Sandbox Code Playgroud)
现在比较
switch (value)
{
case 0:
{
// Do this...
// Do that...
}
break;
case 1:
//and the other...
break;
}
Run Code Online (Sandbox Code Playgroud)
和
switch (value)
{
case 0:
{
// Do this...
// Do that...
if (ObjectWithinScope.Type == Fault)
break;
}
case 1:
{
//and the other...
}
break;
}
Run Code Online (Sandbox Code Playgroud)
当你开始遇到嵌套switch语句的情况时,它确实会变得非常混乱.
只是一个指针.
现在你们中的一些人仍然想知道我在做什么.这里是.一段遗留代码停止工作,没有人能解决原因.这一切都归结为一段代码如下:
switch (value)
{
case 0:
{
// Do this...
// Do that...
if (ObjectWithinScope.Type == Fault)
break;
}
case 1:
{
//and the other...
}
break;
}
Run Code Online (Sandbox Code Playgroud)
确定此代码需要花费很长时间,但在检查更改日志时,它最初是跟随的:
switch (value)
{
case 0:
{
// Do this...
// Do that...
if (ObjectWithinScope.Type == Fault)
// *** A line of code was here ***
break;
}
case 1:
{
//and the other...
}
break;
}
Run Code Online (Sandbox Code Playgroud)
不可否认,原始代码本身并不一致,但是通过在大括号内打破代码在一行代码被意外删除时编译的代码.如果休息时间在括号之外,则不会.