CXX.BITOP.NON_CONST_OPERAND

Bitwise operators should be applied to constants only.

This checker reports defects when a constant expression is not used as an operand for the bitwise operators.

Vulnerability and risk

Performing bitwise operations on non const expressions can lead to unexpected results.

Vulnerable code example

1   void func(int var1, int var2)
2   {  
3     int var4 = var1 | var2; 
4     int var5 = var1 & var2;
5   }

In the above example, lines 3 and 4 are noncompliant as bitwise operators are applied to non const variables. Klocwork produces a CXX.BITOP.NON_CONST_OPERAND defect at lines 3 and 4, indicating, “Bitwise operators should be applied to constants only.”

Fixed code example

1   void func(int var1, int var2)
2   {  
3     int var4 = 5 | 10; 
4     int var5 = 1 & 3;
5   }

In the fixed code example, Klocwork no longer reports the defect CXX.BITOP.NON_CONST_OPERAND at lines 3 and 4.