Your first code fragment is badly indented, it should read:
if (i1)
if (i2)
s1;
else
s2;
Which is equivalent to your second fragment, but obviously very different from the third fragment:
if (i1) {
if (i2)
s1;
} else {
s2;
}
This issue is called the dangling else problem. You can avoid it completely by always using curly braces {
and }
around blocks commanded by if
. You would write the first and second fragments as:
if (i1) {
if (i2) {
s1;
} else {
s2;
}
}
and the third as
if (i1) {
if (i2) {
s1;
}
} else {
s2;
}
Wikipedia has an article about this very issue: https://en.wikipedia.org/wiki/Dangling_else
3
solved Difference betwen “if” sentences with different { structure [closed]