if-else块中的大括号 [英] Curly braces in if-else blocks

查看:84
本文介绍了if-else块中的大括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java编程,却碰巧发现了这个问题:

I'm programming in java and I happened to find myself with this:

if(nodo == null) return null;
    else if(nodo.izquierda!=null && nodo.derecha==null)
        return nodo.izquierda;
    else if(nodo.izquierda==null && nodo.derecha!=null)
        return nodo.derecha;
    else return null; // si ambos hijos son nulos o no nulos

我的问题是:写成这样是否相同:

My question is: Is it the same to write that as:

if(nodo == null) 
    return null;
else {
    if(nodo.izquierda!=null && nodo.derecha==null)
        return nodo.izquierda;
    else {
        if(nodo.izquierda==null && nodo.derecha!=null)
              return nodo.derecha;
        else return null; // si ambos hijos son nulos o no nulos
    }
 }

我对如何在if-else块中使用花括号感到困惑不已.是否需要使用花括号?

More than anything I'm confused by how to use the curly braces with if-else blocks. Is it necesary to use curly braces?

例如:

if (something)
     if (something else)
     ...
     else (blah blah)

与以下相同:

if (something)
{
     if (something else)
     ...
     else (blah blah)
}

推荐答案

例如:

if (something)
      if (something else)
      ...
      else (blah blah)

与以下相同:

 if (something)
   {
      if (something else)
      ...
      else (blah blah)
   }

在这种情况下,是的,它们是相同的,但是前者比后者更难阅读.我建议始终使用大括号,即使对于由一行组成的代码块也是如此.

In this case, yes, they're the same, but the former is harder to read than the latter. I recommend using braces always, even for blocks of code made of a single line.

这篇关于if-else块中的大括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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