#include <iostream>
#include <cstdint>
#include <cstdio>
using namespace std;
int main()
{
uint16_t ii;
std::cin >> ii;
printf("%d\n", ii);
}
When I give input 5
the output is also 5
. But when I change the type of ii
to uint8_t
, I do not get 5
but 53
which seems to be the ASCII value of 5
. Is this expected?
A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.
-fsanitize=unsigned-integer-overflow : Unsigned integer overflow, where the result of an unsigned integer computation cannot be represented in its type. Unlike signed integer overflow, this is not undefined behavior, but it is often unintentional.
— the sign bit has the value −(2N − 1) (one's complement). Nowadays, all processors use two's complement representation, but signed arithmetic overflow remains undefined and compiler makers want it to remain undefined because they use this undefinedness to help with optimization.
In contrast, the C standard says that signed integer overflow leads to undefined behavior where a program can do anything, including dumping core or overrunning a buffer. The misbehavior can even precede the overflow. Such an overflow can occur during addition, subtraction, multiplication, division, and left shift.
uint8_t
is allowed (but not required) to be a typedef for char
(if it happens to be unsigned) or unsigned char
. And input of those is done as characters not numbers. So this is valid but not required behaviour.
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