Consider a function that returns a long long int
value. Even though it returns a long long int
, the logic guarantees that it is always positive. I want to use the return value assigned to an uint64_t
. Given the logic is correct what is the recommended way to do this cast? Should I just assign to it or do a static cast?
-
2`uint64_t to_uint64_t(long long value) { assert(value >= 0); return static_cast
(value); }` – Eljay Jun 28 '20 at 16:45 -
Check if the value is positive than assign it. – just a guy Jun 28 '20 at 16:47
-
`gsl::narrow` if using GSL is an option. Otherwise like Eljay suggested. – Werner Henze Jun 28 '20 at 16:48
-
Does this answer your question? [Efficient unsigned-to-signed cast avoiding implementation-defined behavior](https://stackoverflow.com/questions/13150449/efficient-unsigned-to-signed-cast-avoiding-implementation-defined-behavior) – Andreas is moving to Codidact Jun 28 '20 at 17:42
-
"recommended way to do this cast" -- you're looking for a **conversion**; it might need a cast, but it might not. A **cast** is something you write in your source code to tell the compiler to do a conversion. – Pete Becker Jun 28 '20 at 17:53
1 Answers
This is an implicit conversion, integral convertion, no cast is required:
If the destination type is unsigned, the resulting value is the smallest unsigned value equal to the source value modulo 2n where n is the number of bits used to represent the destination type. That is, depending on whether the destination type is wider or narrower, signed integers are sign-extended or truncated and unsigned integers are zero-extended or truncated respectively.
static_cast
adds no value.
A static_assert
can be used to prevent truncation, e.g.:
static_assert(sizeof(uint64_t) >= sizeof(long long), "Truncation detected.");`
There is also boost::numeric_cast
:
The fact that the behavior for overflow is undefined for all conversions (except the aforementioned unsigned to unsigned) makes any code that may produce positive or negative overflows exposed to portability issues.
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 overflow policy is executed whose default behavior is to throw an an exception (seebad_numeric_cast
,negative_overflow
andpositive_overflow
).

- 131,725
- 17
- 180
- 271