A unary operator is applied twice to the same operand
ID |
c.correctness.no_double_operators |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Control Flow |
Language |
C / C++ |
Description
Reports an expression where a unary prefix operator is applied twice in a row to the same operand: logical negation (!!x), bitwise complement (~~x), or arithmetic negation (- -x).
Rationale
Applying the same unary operator twice cancels it for ~ and arithmetic negation, so ~~x and - -x are exactly equivalent to x and compute nothing useful. !!x does not cancel - it is a common idiom to force any scalar into a canonical 0/1 value - but the other two forms are almost always the visible residue of an edit gone wrong, such as a negation added to an already-negated expression, or two minus signs left behind by a search-and-replace.
The following code illustrates the pattern detected by this rule:
void report(int x, int y)
{
int normalized = !!x;
// FLAGGED: A unary operator is applied twice to the same operand
int complemented = ~~x;
// FLAGGED: A unary operator is applied twice to the same operand
int negated = - -x;
int single_not = !x;
int single_complement = ~x;
int single_negate = -x;
int decrement = --y;
int compound = !(x == y);
}