Dangling Else
ID |
java.dangling_else |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
CWE:483, code-style, reliability |
Description
Reports if statements where an unbraced then-block contains a nested if with an else clause. The else binds to the inner if by language rules, but the programmer may have intended it for the outer if. Adding braces eliminates the ambiguity.
Rationale
The dangling-else ambiguity occurs when nested if statements lack braces. The else always associates with the nearest if, which may not match the indentation or the developer’s intent:
if (a)
if (b)
doX();
else // Binds to 'if (b)', not 'if (a)'
doY();
Remediation
Use braces to make the intended structure explicit:
if (a) {
if (b) {
doX();
} else {
doY(); // Now clearly "a is true but b is false"
}
}