Dela via


C6299

warning C6299: explicitly comparing a bit field to a Boolean type will yield unexpected results

This warning indicates an incorrect assumption that Booleans and bit fields are equivalent. Assigning 1 to bit fields will place 1 in its single bit; however, any comparison of this bit field to 1 includes an implicit cast of the bit field to a signed int. This cast will convert the stored 1 to a -1 and the comparison can yield unexpected results.

Example

The following code generates this warning:

struct myBits
{
  short flag : 1;
  short done : 1;
  //other members
} bitType;

void f( )
{
  if (bitType.flag == 1) 
  {
  // code...
  }
}

To correct this warning, use a bit field as shown in the following code:

void f ()
{
  if(bitType.flag==bitType.done)
  {
    // code...
  }
}