if-else) in Programmingif[-else]: if-elseif-...[-else]A common generalization of if-[else] is a sequence of one or more conditions and associated branches.
The final conditon usually allows a special else, equivalent to using literal true.
The semantics of this generalization can be achieved by repeated nesting inside the else branches of if-else.
The common syntactic convention is then not to increase the indentation with each nesting.
Java, C and C++ take this approach.
Java, C and C++: nesting inside else | Syntactic convention: partially unindented and unbraced |
|---|---|
if (c1) {
s1();
} else {
if (c2) {
s2();
}
}
|
if (c1) {
s1();
} else if (c2) {
s2();
}
|
if (c1) {
s1();
} else {
if (c2) {
s2();
} else {
if (c3) {
s3();
} else {
s4();
}
}
}
|
if (c1) {
s1();
} else if (c2) {
s2();
} else if (c3) {
s3();
} else {
s4();
}
|
Some languages also have a dedicated syntax for the generalization.
In Python, indentation has semantics interfering with unindenting of a nested if,
so an extension to the if-else syntax is provided.
Python: nesting inside else | Dedicated syntax: elif |
|---|---|
if c1:
s1()
else:
if c2:
s2()
else:
if c3:
s3()
else:
s4()
|
if c1: s1() elif c2: s2() elif c3: s3() else: s4() |
In Scheme, unindenting a nested if doesn't change the semantics,
but breaks the syntactic convention for indentation of parentheses.
A separate syntax that doesn't break this convention is provided that also removes the redundant "if"s,
but now requires "else" be explicit.
Scheme: nesting inside else | Dedicated syntax: cond |
|---|---|
(if c1
(s1)
(if c2
(s2)
(if c3
(s3)
(s4))))
|
(cond (c1 (s1)) (c2 (s2)) (c3 (s3)) (else (s4))) |