Message: Same expression in both branches of ternary operator
Category: Logic
Severity: Style
Language: C/C++
This checker detects when syntactically identical expressions appear in both the true and false branches of a ternary operator (condition ? true_expr : false_expr).
The warning is triggered when:
- The second and third operands of a ternary operator are syntactically identical expressions
- This includes cases where variables are referenced through aliases that resolve to the same expression
The same expressions indicates that there might be some logic error or copy paste mistake.
// Same expression in both branches
int result = condition ? x : x; // Warning: duplicateExpressionTernary
// Same variable referenced through alias
const int c = a;
int result = condition ? a : c; // Warning: duplicateExpressionTernary// Different expressions in branches
int result = condition ? x : y; // OK- Check for copy-paste errors: Verify that both branches are supposed to have the same expression
- Use different expressions: If the branches should differ, update one of them
- Simplify the code: If both branches are intentionally the same, remove the ternary operator entirely
Before:
int getValue(bool flag) {
return flag ? computeValue() : computeValue(); // Same computation in both branches
}After:
int getValue(bool flag) {
return computeValue(); // Simplified - condition doesn't matter
}Or if the branches should differ:
int getValue(bool flag) {
return flag ? computeValue() : computeAlternativeValue(); // Different computations
}