Menu

FP integerOverflow?

jacob s
2021-07-09
2021-08-02
  • jacob s

    jacob s - 2021-07-09

    hi,
    given this snippet:

    #include <stdbool.h>
    #include <stdint.h>
    
    #define MSB_SET (1 << 31)
    
    bool nonsense(uint32_t input) {
        return (input & ((uint32_t) MSB_SET)) != 0;
    }
    

    cppcheck gives:

    test.c:7:33: error: Signed integer overflow for expression '1<<31'. [integerOverflow]
        return (input & ((uint32_t) MSB_SET)) != 0;
    

    is that warning correct with the explicit cast?

    thanks, jacob

     
  • CHR

    CHR - 2021-07-09

    I think so, since the overflow happens before the cast. This should fix it: #define MSB_SET (1u << 31).

     
  • Daniel Marjamäki

    I agree with CHR ; technically 1 << 31 is undefined behavior.

    Relevant quote from ISO C99 (6.5.7/4)

    The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated
    bits arelled with zeros. If E1 has an unsigned type, the value of
    the result is E1 × 2**E2, reduced modulo one more than the maximum
    value representable in the result type. If E1 has a signed type and
    nonnegative value, and E1 × 2**E2 is representable in the result
    type, then that is the resulting value; otherwise, the behavior is
    undened.
    

    In this case the type of E1 will be "signed int".

    With 1u there will not be undefined behavior.

     

    Last edit: Daniel Marjamäki 2021-07-09
  • jacob s

    jacob s - 2021-08-02

    right - thanks for your reply!

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.