Comparison is constant¶
ID: cs/constant-comparison Kind: problem Severity: warning Precision: high Tags: - correctness Query suites: - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Comparisons which always yield the same result are unnecessary and may indicate a bug in the logic. This can happen when the data type of one of the operands has a limited range of values. For example unsigned integers are always greater than or equal to zero, and
byte values are always less than 256.
The following expressions always have the same result:
Unsigned < 0is always false,
0 > Unsignedis always false,
0 ≤ Unsignedis always true,
Unsigned ≥ 0is always true,
Unsigned == -1is always false,
Byte < 512is always true.
Examine the logic of the program to determine whether the comparison is necessary. Either change the data types, or remove the unnecessary code.
The following example attempts to count down from
0, however the loop never terminates because
order is an unsigned integer and so the condition
order >= 0 is always true.
for (uint order = numberOfOrders; order >= 0; order--) ProcessOrder(order);
The solution is to change the type of the variable
MSDN Library: C# Operators.