c - 仅在大括号范围内缩进代码是否常见?

标签 c code-formatting

对于生成的代码,我可以选择在仅用于在范围内容纳变量的大括号处缩进或不缩进。目前它没有在这个级别缩进,我想知道我是否要通过缩进来暗示嵌套结构?常见的做法是什么?

/* loop through the total number of letter a rules  */
for (a = 0; a < (number_a_rules - 1); a++) 
{
        /* loop through secondary position rules */           
        {
        int a2end = arulestableend[2];
        for (int a2 = arulestablestart[2]; a2 < a2end; a2++) 
        {
                  /* stuff */
        }
        }
} /* end for a 0 to numberarules -1 */

对比

/* loop through the total number of letter a rules  */
for (a = 0; a < (number_a_rules - 1); a++) 
{
        /* loop through secondary position rules */
        {
                 int a2end = arulestableend[2];
                 for (int a2 = arulestablestart[2]; a2 < a2end; a2++) 
                 {
                     /* stuff */
                 }
        }
} /* end for a 0 to numberarules -1 */

澄清: 使用调试器,额外的缩进意味着难以阅读代码的另一层循环......

最佳答案

在我看来,没有缩进更具误导性。我看着未缩进的版本并想“这里有什么问题”?

真的有必要有多余的大括号吗?

更新

我想回答 ojblass 的评论,它会比我认为的评论占用更多的空间。

I thought you cannot declare variables in c without the braces... at least on some miserable compilers.

您在 C 中不像在 C++ 中那样自由;您需要做的是在任何可执行代码之前放置任何新的声明。所以,在这个片段中

for (a = 0; a < (number_a_rules - 1); a++) 
{
        /* loop through secondary position rules */
        {
                 int a2end = arulestableend[2];
                 for (int a2 = arulestablestart[2]; a2 < a2end; a2++) 

可以写

for (a = 0; a < (number_a_rules - 1); a++) 
{
     int a2end = arulestableend[2];
     for (int a2 = arulestablestart[2]; a2 < a2end; a2++) 

而且它会工作得很好。另一方面,for 循环中的声明也不是直接的 C。

现在,可能的,并且不会在示例中显示的是,如果提问者使用大括号来限制范围,那么他有一个更简单的 namespace 管理;也就是说,所以你可以拥有

{
     int a2 = some_good_thing();
     // do stuff
}
{
     int a2 = something_else();  // Now a different a2, 
                                 // and it's the compiler's problem
     // do other stuff
}

(注意:抱歉,OJ,没意识到你是提问者。我的眼睛受伤了,请根据阅读内容对语法进行必要的更正。)

关于c - 仅在大括号范围内缩进代码是否常见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/764599/

相关文章:

c - 如何在列表中的句柄上使用 free?-> C -> Windows API

c - 打印每个宽字符字节的字符值

java - Eclipse Java 格式化程序 : blank lines

javascript - 使用 --fix 运行时 ESLint 错误 'Invalid count value'

.net - 有什么方法可以在 Brace ( } ) 完成时禁用 ReSharper Web Form/MVC (.aspx) 代码格式?

java - 为什么 GetLastError() 会阻止我的方法?

c - 了解 C 宏语法和函数

python - 网页抓取时如何将数据写入 csv 中的新列?

c - 灵活的数组成员,不必是最后一个

java - Javascript 的最佳源代码格式化程序?