Bad check for oddness¶
ID: cpp/incomplete-parity-checkKind: problemSecurity severity: Severity: warningPrecision: mediumTags: - reliability - correctness - typesQuery suites: - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
This rule finds code that usesx%2==1 to check whether a numberx is odd, which does not work for negative numbers. Applying% to negative numbers produces negative results. For example,(-5)%2 equals-1, not1. As a result, this check incorrectly considers all negative numbers as even.
Recommendation¶
Consider usingx%2!=0 or(x&1)==1 instead.
References¶
MSDN Library:Multiplicative Operators and the Modulus Operator.
Wikipedia:Modulo Operation - Common pitfalls.