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
I think so, since the overflow happens before the cast. This should fix it: #define MSB_SET (1u << 31).
#define MSB_SET (1u << 31)
I agree with CHR ; technically 1 << 31 is undefined behavior.
1 << 31
Relevant quote from ISO C99 (6.5.7/4)
The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled 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 undefined.
In this case the type of E1 will be "signed int".
With 1u there will not be undefined behavior.
1u
right - thanks for your reply!
Log in to post a comment.
hi,
given this snippet:
cppcheck gives:
is that warning correct with the explicit cast?
thanks, jacob
I think so, since the overflow happens before the cast. This should fix it:
#define MSB_SET (1u << 31)
.I agree with CHR ; technically
1 << 31
is undefined behavior.Relevant quote from ISO C99 (6.5.7/4)
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
right - thanks for your reply!