Search code examples
c++visual-c++overflowinteger-overflow

What's an efficient way to avoid integer overflow converting an unsigned int to int in C++?


Is the following an efficient and problem free way to convert an unsigned int to an int in C++:

#include <limits.h>
void safeConvert(unsigned int passed) 
{
    int variable = static_cast<int>(passed % (INT_MAX+1)); 
    ...
}

Or is there a better way?

UPDATE

As pointed out by James McNellis it is not undefined to assign an unsigned int > INT_MAX to an integer - rather this is implementation defined. As such the context here is now specifically on my preference is to ensure this integer resets to zero when the unsigned int exceeds INT_MAX.

Original Context

I have a number of unsigned int's used as counters, but want to pass them around as integers in a specific case.

Under normal operation these counts will remain within the bounds of INT_MAX. However to avoid running into undefined implementation specific behaviour should the abnormal (but valid) case occur I want some efficient conversion here.


Solution

  • This should also work:

    int variable = passed & INT_MAX;