Dangling Else-If Chains is one of the source-code metrics Understand computes across 17+ languages — browse them in the GUI, export and track them, or script them with the Python API.
Dangling Else-If Chains
API ID: CountDanglingElseIfLanguages: Any
Targets: Functions
The number of if/else-if chains in a function that have no final else
An if statement extended by at least one else-if but not closed by an else leaves one case unhandled. Whether that case was overlooked is not visible from the code, which is why several coding standards require the final else. A plain if with no else-if is not counted, because a single guarded statement is normal.
Chains are counted once each, at the leading if, so nested chains are
counted separately from the chain that contains them. An else that opens a
block and happens to start with an if, else { if (x) ... }, is
a terminating else and does not extend the chain.
Example:
int dangling(int x) // CountDanglingElseIf = 1
{
if (x > 0)
return 1;
else if (x < 0) // +1 the chain never ends in an else
return 2;
return 0;
}
int closed(int x) // CountDanglingElseIf = 0
{
if (x > 0)
return 1;
else if (x < 0)
return 2;
else // the chain ends in an else
return 3;
}
int plainIf(int x) // CountDanglingElseIf = 0
{
if (x > 0) // no else-if, so no chain
return 1;
return 0;
}