How can we properly check and handle for an overflow when we cast to uint32_t
, for example:
long int val = <some value>
uint32_t new_val = static_cast<uint32_t>(val);
If I try the above, I get an expected conversion error:
error: conversion to ‘uint32_t {aka unsigned int}’ from ‘long int’ may alter its value [-Werror=conversion]
As seen here, I need to compare val
against INT_MAX
and INT_MIN
but to allow me to understand and learn about this I would appreciate a brief explanation of what is the best way to check for overflow in a case like the above.