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

Copy
   void func(int var1, int var2)
   {  
     int var4 = var1 | var2; 
     int var5 = var1 & var2;
   }

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

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

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