Both operands of an operator are the same

tx0/c:identical-operandsdefaultwarningbug

What it finds

a == a, n - n, x && x: an operator whose operands are the same expression gives a result known in advance, or the operand itself, and one of the two operands was usually meant to be something else, as in a.x == a.x for a.x == b.x.

For floating-point values x != x tests for NaN and x - x can be NaN, so the rule needs to know the types: every name in the operands must be declared in the file with a type that is an integer, an enum or a pointer, as far as [crate::types] can tell, and not volatile, since reading a volatile object twice can give two values. No operand may hold a call, which may be a macro, a cast or a floating literal, and expressions given to a macro or inside sizeof are left alone. Operands made of constants alone, as REG_X - REG_X for the offset of a register from a base that happens to be the same, are written so on purpose.

From the rule's source, identical_operands.rs.

Example from the rule's tests
#include <stddef.h> enum reg { REG_BASE = 4, REG_CTRL = 4 }; struct point {  int x;  double weight;  volatile unsigned status;}; int compare(struct point *a, struct point *b, int n, unsigned u, size_t len, char *s, double d){  int r = 0;  if (a->x == a->x)tx0 reports: both operands of == are a->x    r++;  r += n - n;tx0 reports: both operands of - are n  r += (u & u);tx0 reports: both operands of & are u  if (len != len)tx0 reports: both operands of != are len    r++;  if (s < s)tx0 reports: both operands of < are s    r++;  if (n > 0 && n > 0)tx0 reports: both operands of && are n > 0    r++;  if (a->x == b->x)    r++;  if (d != d)    r++;  if (a->weight == a->weight)    r++;  if (a->status == a->status)    r++;  r += REG_CTRL - REG_BASE;  r += REG_BASE - REG_BASE;  r += n + n;  r += n * n;  return r + (int)sizeof(n == n);}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/c:identical-operands" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/c:identical-operands] reason="..."

tx0 explain tx0/c:identical-operands shows the same in the terminal. Found a false positive? Report it.