C & C++

C & C++

Made by DeepSource

Found redundant cloned branches CXX-W2041

Anti-pattern
Minor

Found repeated branches in if/else statements, consecutive repeated branches in switch statements, and identical true and false branches in conditional operators.

In the bad practice example, the then and else branches are identical, which can be considered redundant. The code can be simplified by removing the conditional statement and executing the shared code unconditionally.

However, if this is the intended behavior, there is no reason to use a conditional statement in the first place.

The check also detects repeated branches in longer if/else if/else chains, where it can be harder to notice the problem. In switch statements, the check reports repeated branches only when they are consecutive. This is because the case labels often have a natural ordering, and rearranging them would decrease code readability.

For example:

switch (ch) {
case 'a':
  return 10;
case 'A':
  return 10;
case 'b':
  return 11;
case 'B':
  return 11;
default:
  return 10;
}

In this case, the check reports that the 'a' and 'A' branches are identical (and that the 'b' and 'B' branches are also identical), but it does not report that the default branch is also identical to the first two branches.

If preserving the order of branches is important, the repeated branches can be combined using multiple case labels:

switch (ch) {
case 'a':
case 'A':
  return 10;
case 'b':
case 'B':
  return 11;
default:
  return 10;
}

In this case, the check does not warn for the repeated return 10;, as it helps preserve the order of branches.

The check also examines conditional operators and reports code where the true and false branches are identical:

return test_value(x) ? x : x;

Unlike if statements, the check does not detect chains of conditional operators.

Note: This check also reports situations where branches become identical only after preprocessing.

Bad Practice

if (test_value(x)) {
  y++;
  do_something(x, y);
} else {
  y++;
  do_something(x, y);
}

Recommended

test_value(x); // can be omitted unless it has side effects
y++;
do_something(x, y);