C 在每个案例之后切换案例花括号 [英] C Switch-case curly braces after every case

查看:17
本文介绍了C 在每个案例之后切换案例花括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C switch-case 流控制中,如果变量在那个块.

In a C switch-case flow control, it's required to put curly braces { } after a case if variables are being defined in that block.

不管变量声明如何,在每个 case 之后都放大括号是不好的做法吗?

Is it bad practice to put curly braces after every case, regardless of variable declaration?

例如:

switch(i) {
  case 1: {
    int j = 4;
    ...code...
  } break;

  case 2: {  //No variable being declared! Brace OK?
    ...code...
  } break;
}

推荐答案

在每个 case 块中使用大括号当然不是无效的,也不一定是不好的样式.如果你因为变量声明而有一些带大括号的 case 块,给其他的加大括号可以使编码风格更加一致.

It's certainly not invalid to use braces in every case block, and it's not necessarily bad style either. If you have some case blocks with braces due to variable declarations, adding braces to the others can make the coding style more consistent.

话虽如此,在 C 语言的 case 块中声明变量可能不是一个好主意.虽然编译器可能允许这样做,但可能有更简洁的解决方案.互斥的 case 块可能能够共享几个常见的临时变量,或者您可能会发现您的 case 块作为辅助函数会更好地工作.

That being said, it's probably not a good idea to declare variables inside case blocks in straight C. While that might be allowed by your compiler, there's probably a cleaner solution. Mutually-exclusive case blocks may be able to share several common temporary variables, or you may find that your case blocks would work better as helper functions.

这篇关于C 在每个案例之后切换案例花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆