Click on image to see enlargment

PC-lint/FlexeLint Output | Reference Manual Explanation | Home Page

            bug648.cpp

1     #include <stdio.h>
2
3     #define TwoToThePowerOf(n) (2 << (n))
4
5     bool TestSignBit( int n )
6         {
7         if( TwoToThePowerOf(31) & n ) return true;
8         else return false;
9         }
10
11    int main()
12        {
13        printf( "%d is %s\n", -1, TestSignBit(-1) ? "negative" : "positive" );
14        return 0;
15        }

Our programmer receives the message that "-1 is positive". That just can't be right. What's his mistake?


bug648.cpp lint Output

--- Module:   bug648.cpp
                          _
    if( TwoToThePowerOf(31) & n ) return true;
bug648.cpp(7) : Warning 648: Overflow in computing constant for operation:
    'shift left'
bug648.cpp(7) : Info 778: Constant expression evaluates to 0 in operation '<<'
bug648.cpp(7) : Info 774: Boolean within 'if' always evaluates to False
    [Reference: file bug648.cpp: line 7]

Reference Manual Explanation

 
648   Overflow in computing constant for operation: String  --
      Arithmetic overflow was detected while computing a
      constant expression.  For example, if int is 16 bits then
      200 * 200 will result in an overflow. String gives the
      operation that caused the overflow and may be one of:
      addition, unsigned addition, multiplication, unsigned
      multiplication, negation, shift left, unsigned shift left,
      subtraction, or unsigned sub.

      To suppress this message for particular constant
      operations you may have to supply explicit truncation.
      For example, if you want to obtain the low order 8 bits of
      the integer 20000 into the high byte of a 16-bit int,
      shifting left would cause this warning.  However,
      truncating first and then shifting would be OK.  The
      following code illustrates this where int is 16 bits.

            20000u << 8;                  /* 648 */
            (0xFF & 20000u) << 8;         /* OK  */
      If you truncate with a cast you may make a signed
      expression out of an unsigned.  For example, the following
      receives a warning (for 16 bit int).

            (unsigned char) OxFFFu << 8       /* 648 */

      because the unsigned char is promoted to int before
      shifting.  The resulting quantity is actually negative.
      You would need to revive the unsigned nature of the
      expression with

            (unsigned) (unsigned char) OxFFF << 8     /* OK */

[ new ] Use our Interactive Demo to Run FlexeLint on our Bugs of the Month

PC-lint/FlexeLint - Product Overview

Home | Contact | Order

PC-lint and FlexeLint are trademarks of Gimpel Software
Copyright 2007, Gimpel Software, All rights reserved.