if 语句的格式 [英] Formatting of if Statements

查看:22
本文介绍了if 语句的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是圣战,也不是哪个更好"的问题.

对单个语句 if 块使用以下格式的优点是什么.

What are the pros of using the following format for single statement if blocks.

if (x) print "x is true";

if(x) 
    print "x is true";

相对于

if (x) { print "x is true"; }
if(x) {
    print "x is true";    
}

如果您格式化没有括号的单个语句 ifs 或知道这样做的程序员,首先是什么促使您/他们采用这种风格?我对这给您带来了哪些好处特别感兴趣.

If you format your single statement ifs without brackets or know a programmer that does, what led you/them to adopt this style in the first place? I'm specifically interested in what benefits this has brought you.

更新:由于最受欢迎的答案忽略了实际问题(即使它提出了最合理的建议),这里是无括号的专业人士的综述.

Update: As the most popular answer ignores the actual question (even if it presents the most sane advice), here's a roundup of the bracket-less pros.

  1. 紧凑性
  2. 对某些人来说更具可读性
  3. 括号调用范围,在某些情况下会产生理论上的开销

推荐答案

总是使用大括号是个好主意,但标准答案总是给出如果有人添加一行代码而忘记添加大括号怎么办?"是一个相当薄弱的理由.

Always using braces is a good idea but the standard answer that's always given "what if somebody adds a line of code and forgets to add the braces?" is a rather weak reason.

从一开始就没有大括号可能会引入一个微妙的错误.这种情况在我身上发生过几次,我也见过其他程序员发生过.

There is a subtle bug which can be introduced by not having the braces from the start. It's happened to me a few times and I've seen it happen to other programmers.

它以一个简单的 if 语句开始.

It starts out, innocently enough, with a simple if statement.

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

这一切都很好.

然后有人来为 if 添加另一个条件.他们不能使用 && 添加它到 if 语句本身,因为逻辑不正确,所以他们添加了另一个 if.我们现在有:

Then someone comes along and adds another condition to the if. They can't add it using && to the if statement itself because the logic would be incorrect, so they add another if. We now have:

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

你看到问题了吗?它可能看起来是正确的,但编译器会以不同的方式看待它.它是这样看的:

Do you see the problem? It may look right but the compiler sees it differently. It sees it like this:

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

这意味着完全不同的东西.编译器不关心格式.else 与最近的 if 一起使用.而另一方面,人类依赖于格式设置,很容易错过问题.

Which means something completely different. The compiler doesn't care about formatting. The else goes with the nearest if. Humans, on the other hand, rely on formatting and can easily miss the problem.

这篇关于if 语句的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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