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

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

问题描述

这不是一个神圣的战争,这是不是哪个更好的问题。

什么是使用以下格式,如果单块语句的利弊。

 如果(x)的打印X是真的;如果(X)
    打印X是真的;

相对于

 如果(X){打印X是真的; }
如果(X){
    打印X是真的;
}

如果您格式化单个语句IFS没有括号或认识的程序员,做,是什么促使你/他们首先采用这种风格?我在什么好处这给你带来了特别感兴趣。

更新:作为最受欢迎的答案是忽略了实际问题(即使presents最明智的建议),这里的支架少利弊的综述


  1. 压实

  2. 更可读一些

  3. 括号调用范围,其具有在一些情况下,理论上的开销


解决方案

始终使用括号是一个好主意,但标准答案总是给出是什么,如果有人添加一行code和忘记的加括号? 是相当弱的原因。

有是可以由没有从一开始就在大括号推出一个微妙的错误。它发生在我身上了几次,我已经看到了发生在其他的程序员。

它开始了,非常无辜地如果一个简单的声明。

 如果(条件)
    做一点事();
其他
    do_something_else的();

这是一切都很好。

这时,有人走来,并增加了一个条件,如果该。使用与放他们不能添加它;&安培; if语句本身因为逻辑是不正确的,所以他们如果添加另一个。我们现在有:

 如果(条件)
    如果(条件2)
        做一点事();
其他
    do_something_else的();

你看这个问题?它可能看起来正确的,但编译器看到不同的看法。它认为这样的:

 如果(条件)
    如果(条件2)
        做一点事();
    其他
        do_something_else的();

这意味着完全不同的东西。编译器不关心格式。该其他的都与最近的如果。人类,在另一方面,靠格式,而且可以很容易地错过了问题。

This isn't a holy war, this isn't a question of "which is better".

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";

As opposed to

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

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. Compactness
  2. More readable to some
  3. Brackets invoke scope, which has a theoretical overhead in some cases

解决方案

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.

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

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

Which is all well and good.

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();

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天全站免登陆