在哪里放置switch/case语句与块

jac*_*hab 18 c++ syntax

当我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)

谢谢.

Ind*_*000 21

这是一种风格问题.

我会把break结束支架放在外面,以使其更具可读性.

  • 同意.不同意(我认为它内部更具可读性,但这只是我的风格:-0) (5认同)

ava*_*kar 15

你把它放在任何你喜欢的地方.确保在整个项目中保持一致.(就个人而言,我把它放在外面.)


Chr*_*sBD 5

它应该出现在.

例如:

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)

不可否认,原始代码本身并不一致,但是通过在大括号内打破代码在一行代码被意外删除时编译的代码.如果休息时间在括号之外,则不会.

  • "应该" ?为什么? (7认同)