对于单行if或循环使用大括号(即{})的目的是什么?

本文翻译自:What's the purpose of using braces (i.e. {}) for a single-line if or loop?

I'm reading some lecture notes of my C++ lecturer and he wrote the following: 我正在阅读我的C ++讲师的一些讲义,他写了以下内容:

  1. Use Indentation // OK 使用缩进//确定
  2. Never rely on operator precedence - Always use parentheses // OK 永远不要依赖运算符优先级 - 始终使用括号//确定
  3. Always use a { } block - even for a single line // not OK , why ??? 总是使用{}块 - 即使是单行// 不行 ,为什么???
  4. Const object on left side of comparison // OK 比较左侧的Const对象// OK
  5. Use unsigned for variables that are >= 0 // nice trick 对于> = 0 //好玩法的变量使用无符号
  6. Set Pointer to NULL after deletion - Double delete protection // not bad 删除后将指针设置为NULL - 双删除保护//不错

The 3rd technique is not clear to me: what would I gain by placing one line in a { ... } ? 第三种技术对我来说并不清楚:在{ ... }放置一行会获得什么?

For example, take this weird code: 例如,拿这个奇怪的代码:

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
{
    if (i % 2 == 0)
    {
        j++;
    }
}

and replace it with: 并替换为:

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
    if (i % 2 == 0)
        j++;

What's the benefit of using the 1st version? 使用第一个版本有什么好处?


#1楼

参考:https://stackoom.com/question/pA02/对于单行if或循环使用大括号-即-的目的是什么


#2楼

Let's attempt to also modify i when we increment j : 当我们递增j时,让我们尝试修改i

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
    if (i % 2 == 0)
        j++;
        i++;

Oh no! 不好了! Coming from Python, this looks ok, but in fact it isn't, as it's equivalent to: 来自Python,这看起来不错,但实际上并非如此,因为它相当于:

int j = 0;
for (int i = 0 ; i < 100 ; ++i)
    if (i % 2 == 0)
        j++;
i++;

Of course, this is a silly mistake, but one that even an experienced programmer could make. 当然,这是一个愚蠢的错误,但即使是经验丰富的程序员也可以做到。

Another very good reason is pointed out in ta.speot.is's answer . ta.speot.is的回答中指出了另一个很好的理由

A third one I can think of is nested if 's: 我能想到的第三个是嵌套if

if (cond1)
   if (cond2) 
      doSomething();

Now, assume you now want to doSomethingElse() when cond1 is not met (new feature). 现在,假设您现在想要在cond1cond1 doSomethingElse() (新功能)。 So: 所以:

if (cond1)
   if (cond2) 
      doSomething();
else
   doSomethingElse();

which is obviously wrong, since the else associates with the inner if . 这显然是错误的,因为else与内部同事if


Edit: Since this is getting some attention, I'll clarify my view. 编辑:由于这引起了一些关注,我将澄清我的观点。 The question I was answering is: 我回答的问题是:

What's the benefit of using the 1st version? 使用第一个版本有什么好处?

Which I have described. 我已经描述过了。 There are some benefits. 有一些好处。 But, IMO, "always" rules don't always apply. 但是,IMO,“永远”规则并不总是适用。 So I don't wholly support 所以我不完全支持

Always use a { } block - even for a single line // not OK, why ??? 总是使用{}块 - 即使是单行//不行,为什么???

I'm not saying always use a {} block. 我并不是说总是使用{}块。 If it's a simple enough condition & behavior, don't. 如果这是一个简单的条件和行为,不要。 If you suspect someone might come in later & change your code to add functionality, do. 如果您怀疑有人可能会稍后进入并更改您的代码以添加功能,请执行此操作。


#3楼

it is more intuitive and easily understandable. 它更直观,更容易理解。 It makes the intent clear. 它使意图清晰。

And it ensures that the code doesn't break when a new user might unknowingly miss the { , } while adding a new code statement. 并且它确保当新用户在添加新代码语句时可能在不知不觉中错过{}时代码不会中断。


#4楼

It's very easy to accidentally change control-flow with comments if you do not use { and } . 如果不使用{}则很容易通过注释意外更改控制流。 For example: 例如:

if (condition)
  do_something();
else
  do_something_else();

must_always_do_this();

If you comment out do_something_else() with a single line comment, you'll end up with this: 如果你用单行评论注释掉do_something_else() ,你最终会得到:

if (condition)
  do_something();
else
  //do_something_else();

must_always_do_this();

It compiles, but must_always_do_this() isn't always called. 它编译,但must_always_do_this()并不总是被调用。

We had this issue in our code base, where someone had gone in to disable some functionality very quickly before release. 我们在代码库中遇到了这个问题,有人在发布之前很快就禁用了某些功能。 Fortunately we caught it in code review. 幸运的是,我们在代码审查中发现了它。


#5楼

It makes your code more readable by clearly defining the scope of your loops and conditional blocks. 它通过清楚地定义循环和条件块的范围,使您的代码更具可读性。 It also saves you from accidental mistakes. 它还可以避免意外错误。


#6楼

If you are a compiler, it doesn't make any difference. 如果您是编译器,它没有任何区别。 Both are the same. 两者都是一样的。

But for programmers, the first one is more clear, easy to read and less error-prone. 但对于程序员来说,第一个更清晰,易于阅读且不易出错。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值