#include <limits.h>
int main(){
int a = UINT_MAX;
return 0;
}
I this UB or implementation defined?
Links saying its UB
https://www.gnu.org/software/autoconf/manual/autoconf-2.63/html_node/Integer-Overflow-Basics
Allowing signed integer overflows in C/C++
Links saying its Implementation defined
Conversion rule says:
Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
Aren't we converting a max unsigned value
into a signed value
?
The way I have seen it, gcc just truncates the result.
Both references are correct, but they do not address the same issue.
int a = UINT_MAX;
is not an instance of signed integer overflow, this definition involves a conversion fromunsigned int
toint
with a value that exceeds the range of typeint
. As quoted from the École polytechnique's site, the C Standard defines the behavior as implementation-defined.Here is the text from the C Standard:
Some compilers have a command line option to change the behavior of signed arithmetic overflow from undefined behavior to implementation-defined:
gcc
andclang
support-fwrapv
to force integer computations to be performed modulo the 232 or 264 depending on the signed type. This prevents some useful optimisations, but also prevents some counterintuitive optimisations that may break innocent looking code. See this question for some examples: What does -fwrapv do?