2 ms·
So what's the correct way to tell the C++ compiler you want integer overflow to occur in a particular spot when overflow trapping is enabled?
by himinlomax 6y ago
So what's the correct way to tell the C++ compiler you want integer overflow to occur in a particular spot when overflow trapping is enabled?
- rocqua 6y agoUse `unsigned int` instead of `int` Overflow for signed types is undefined behavior. Hence the compiler can trap when it happens and remain standards compliant. For unsigned types, overflow is defined behavior, and hence -ftrap will not trigger on overflow. An interesting flip side of this is that using signed types can be a lot faster because the compiler is allowed to assume that overflow will not happen, which lets it apply more optimizations.
- bregma 6y agoSince most compiler vendors provide an implementation-specific way to define the undefined behaviour of signed integer overflow as a vendor extension, you will need to resort to compiler-specific means to control that. For example, in GCC you could use a `#pragma push_options("-fno-trapv")/#pragma GCC pop_options` pair to surround the offending code.