Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weird gcc behavior with unsigned ints

Tags:

c++

c++11

g++

c++14

#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?

like image 648
gyro Avatar asked Dec 27 '14 13:12

gyro


People also ask

What happens when unsigned int overflows?

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.

Is unsigned overflow undefined Behaviour?

-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.

Why is signed integer overflow undefined Behaviour?

— 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.

Is overflow undefined in C?

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.


1 Answers

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.

like image 168
Alan Stokes Avatar answered Nov 02 '22 06:11

Alan Stokes