mercredi 13 mai 2015

Curly braces in if-else blocks

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
    }
 }

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

For example:

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

Is the same that:

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

Aucun commentaire:

Enregistrer un commentaire