Dela via


C6240

warning C6240: (<expression> && <non-zero constant>) always evaluates to the result of <expression>. Did you intend to use the bitwise-and operator?

This warning indicates that a non-zero constant value, other than one, was detected on the right side of a logical-and operation that occurs in a test context. For example, the expression (n && 3) reduces to (!!n), which is the Boolean value of n.

This warning typically indicates an attempt to check a bit mask in which the bitwise-AND (&) operator should be used. It is not generated if the non-zero constant evaluates to 1 because of its use for selectively choosing code paths.

Example

The following code generates this warning:

#include <stdio.h>
#define INPUT_TYPE 2

void f(int n)
{
   if (n && INPUT_TYPE) 
   {
      puts("boolean value of !!n is true");
   }
   else
   {
      puts("boolean value of !!n is false");
   }
}

To correct this warning, use bitwise-AND operator as shown in the following code:

#include <stdio.h>
#define INPUT_TYPE 2

void f(int n)
{
   if ( (n & INPUT_TYPE) )
   {
      puts("bitmask true");
   }
   else
   {
      puts("bitmak false");
   }
}

See Also

Reference

& Operator (C# Reference)