Home > Mobile >  Converting Integer Types
Converting Integer Types

Time:09-15

How does one convert from one integer type to another safely and with setting off alarm bells in compilers and static analysis tools?

Different compilers will warn for something like:

int i = get_int();
size_t s = i;

for loss of signedness or

size_t s = get_size();
int i = s;

for narrowing.

casting can remove the warnings but don't solve the safety issue.

Is there a proper way of doing this?

CodePudding user response:

You can try boost::numeric_cast<>.

boost numeric_cast returns the result of converting a value of type Source to a value of type Target. If out-of-range is detected, an exception is thrown (see bad_numeric_cast, negative_overflow and positive_overflow ).

CodePudding user response:

How does one convert from one integer type to another safely and with setting off alarm bells in compilers and static analysis tools?

Control when conversion is needed. As able, only convert when there is no value change. Sometimes, then one must step back and code at a higher level. IOWs, was a lossy conversion needed or can code be re-worked to avoid conversion loss?

It is not hard to add an if(). The test just needs to be carefully formed.

Example where size_t n and int len need a compare. Note that positive values of int may exceed that of size_t - or visa-versa or the same. Note in this case, the conversion of int to unsigned only happens with non-negative values - thus no value change.

int len = snprintf(buf, n, ...);
if (len < 0 || (unsigned)len >= n) {
  // Handle_error();
}
  •  Tags:  
  • c c
  • Related