I have just joined a team that has thousands of lines of code like:
int x = 0;
x=something();
short y=x;
doSomethingImportantWith(y);
The compiler gives nice warnings saying: Conversion of XX bit type value to "short" causes truncation. I've been told that there are no cases where truncation really happens, but I seriously doubt it.
Is there a nice way to insert checks into each case having the effect of:
if (x>short.max) printNastyError(__FILE,__LINE);
before each assignment? Doing this manually will take more time and effort than I'd like to use, and writing a script that reads the warnings and adds this stuff to the correct file as well as the required includes seems overkill -- especially since I expect someone has already done this (or something like it).
I don't care about performance (really) or anything other than knowing when these problems occur so I can either fix only the ones that really matter, or so I can convince management that it's a problem.
You could try compiling and running it with the following ugly hack:
#include <limits>
#include <cstdlib>
template<class T>
struct IntWrapper
{
T value;
template<class U>
IntWrapper(U u) {
if(u > std::numeric_limits<T>::max())
std::abort();
if(U(-1) < 0 && u < std::numeric_limits<T>::min()) // for signed U only
std::abort();
value = u;
}
operator T&() { return value; }
operator T const&() const { return value; }
};
#define short IntWrapper<short>
int main() {
int i = 1, j = 0x10000;
short ii = i;
short jj = j; // this aborts
}
Obviously, it may break code that passes short as a template argument and likely in other instances, so undefine it where it breaks the build. And you may need to add operator overloads so that the usual arithmetic works with the wrapper.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With