...
Type range errors, including loss of data (truncation) and loss of sign (sign errors), can occur when converting from a value of a signed type to a value of an unsigned type. This noncompliant code example results in a loss of sign:negative number being misinterpreted as a large positive number.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <limits.h> void func(void) { signed int si = INT_MIN;) { /* Cast eliminates warning */ unsigned int ui = (unsigned int)si; /* ... */ } /* ... */ func(INT_MIN); |
Compliant Solution (Signed to Unsigned)
...
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 */ } /* ... */ } /* ... */ func(INT_MIN + 1); |
Subclause 6.2.5, paragraph 9, of the C Standard [ISO/IEC 9899:2011] provides the necessary guarantees to ensure this solution works on a conforming implementation:
...