Reputation: 118
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)
}
Upvotes: 2
Views: 11240
Reputation: 79
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;
Upvotes: -1
Reputation: 4148
else if
, the else if
always belongs to the innermost if
statement.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();
}
}
Upvotes: 2
Reputation: 85779
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.
Upvotes: 7
Reputation: 26185
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.
Upvotes: 1
Reputation: 21
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.
Upvotes: 2