3 ms·
The reason why this is not signaled as an error in C/C++ with -ftrapv is because of the implicit integer truncation on assignment/initialization, which does not
by adrian_b 5y ago
The reason why this is not signaled as an error in C/C++ with -ftrapv is because of the implicit integer truncation on assignment/initialization, which does not give errors in C/C++.
In C/C++, when -x is computed, x is promoted to int, so "-" does not overflow and "-ftrapv" does not matter.
This would be harmless, except that "return -x" truncates the result to 8 bits, which overflows, but this truncation is not checked so it does not signal an overflow exception, as it should in a decent programming language.
Had x been an "int", instead of an "int8_t", the error would have been caught in C/C++ with -ftrapv (when "-" is applied to INT_MIN), but "int16_t" would have also resulted in an error that is not caught, due to implicit unchecked truncation.
While forbidding all implicit conversions is a serious mistake in the opposite direction, many of the implicit conversions that exist in C/C++ for historical reasons are extremely harmful and they should be avoided like the plague, i.e. the truncation of larger integers into smaller integers and also the implicit conversions of signed integers into unsigned integers.