...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <limits.h> void func(void) { signed int si = INT_MIN; unsigned int ui; if (si < 0) { /* Handle error */ } else { ui = (unsigned int)si; /* Cast eliminates warning */ } /* ... */ } |
Subclause 6.2.5 paragraph 9 of the C Standard [ISO/IEC 9899:2011] provides the necessary guarantees to ensure this solution works on an conforming implementation:
The range of nonnegative values of a signed integer type is a subrange of the corresponding unsigned integer type, and the representation of the same value in each type is the same.
Noncompliant Code Example (Signed, Loss of Precision)
...