问题
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)
}
回答1:
For example:
if (something) if (something else) ... else (blah blah)
Is the same that:
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.
回答2:
For Java, curly braces are optional for if-else statements. As Jared stated, only the next statement will be executed when curly braces are omitted.
Generally the braces help with organization and readability of the code, so they commonly will be used.
回答3:
else if
, the else if
always belongs to the innermost if
statement.REFERENCE: Link to the IF ELSE behavior if braces are Omitted
if
to else if
and else
when there are braces that are indent-aligned.if (var1 == 1) {
action1();
}
else if (var1 == 2) {
action2();
}
else if (var1 == 3) {
if (var2 == 1) {
action31();
}
else if (var2 == 2) {
action32();
}
}
回答4:
My question is: Is it the same to write that as:
The fact that you need to ask is a very good reason to use the braces. There are always two audiences for code, a compiler and any human who may need to read and reason about the code, including your own future self.
Often, braces will be unnecessary for the compiler, but enhance readability for the other audience.
回答5:
if(nodo != null)
if(nodo.izquierda != null && nodo.derecha == null)
return nodo.izquierda;
else if(nodo.izquierda == null && nodo.derecha != null)
return nodo.derecha;
return null;
来源:https://stackoverflow.com/questions/30224071/curly-braces-in-if-else-blocks