...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <limits.h> #include <stddef.h> #include <inttypes.h> extern size_t popcount(uintmax_t); #define UWIDTH(x) popcount(x) void func(signed long si_a, signed long si_b) { signed long result; if ((si_a < 0) || (si_b < 0) || (si_b >= UWIDTH(ULONG_MAX)) || (si_a > (LONG_MAX >> si_b))) { /* Handle error */ } else { result = si_a << si_b; } /* ... */ } |
The UWIDTH()
macro provides the correct width for an unsigned integer type (see INT19-C. Correctly compute integer widths). This solution also complies with INT34-C. Do not shift a negative number of bits or more bits than exist in the operand.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <limits.h> #include <stddef.h> #include <inttypes.h> extern size_t popcount(uintmax_t); #define UWIDTH(x) popcount(x) void func(unsigned int ui_a, unsigned int ui_b) { unsigned int uresult = 0; if (ui_b >= UWIDTH(unsigned int, UINT_MAX)) { /* Handle error condition */ } else { uresult = ui_a << ui_b; } /* ... */ } |
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <limits.h> #include <stddef.h> #include <inttypes.h> extern size_t popcount(uintmax_t); #define UWIDTH(x) popcount(x) void func(unsigned int ui_a, unsigned int ui_b) { unsigned int uresult = 0; if (ui_b >= UWIDTH(unsigned int, UINT_MAX)) { /* Handle error condition */ } else { uresult = ui_a >> ui_b; } /* ... */ } |
...