Reputation: 1483
Code:
#include <cstdio>
int main() {
unsigned char a = -300.f;
printf("%d\n", a);
}
GCC compiling:
g++ test.cpp -o test -std=c++11
test.cpp: In function ‘int main()’:
test.cpp:4:21: warning: overflow in implicit constant conversion [-Woverflow]
unsigned char a = -300.f;
^
GCC result:
0
GCC version:
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609
Clang Compiling:
clang++ test.cpp -o test -std=c++11
test.cpp:4:21: warning: implicit conversion from 'float' to 'unsigned char' changes value from 300 to 255
[-Wliteral-conversion]
unsigned char a = -300.f;
~ ^~~~~
1 warning generated.
Clang result:
160
Clang version:
clang version 3.8.0-2ubuntu4 (tags/RELEASE_380/final)
Maybe the standard doesn't define this behavior.
After adding -fsanitize=undefined
:
GCC result (same):
0
Clang result (48!?):
test.cpp:4:20: runtime error: value -300 is outside the range of representable values of type 'unsigned char'
48
Upvotes: 2
Views: 178
Reputation: 234875
The behaviour on converting a floating point type to an unsigned char
where the floating point value is outside the range of the unsigned char
is undefined.
Note this is different to the case where the original type is a wider integral type.
Upvotes: 6