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

Columbo
  • 60,038
  • 8
  • 155
  • 203
gyro
  • 178
  • 3
  • 13
  • But, I have used printf not cout right. Isn't the problem with cin? – gyro Dec 27 '14 at 13:41
  • printing is also problematic, why do you cast to `uint8_t`? – Karoly Horvath Dec 27 '14 at 13:45
  • @KarolyHorvath right..the way I print is also wrong. But somehow it prints right value.. Not sure why though – gyro Dec 27 '14 at 14:08
  • as it is usually with C & C++, this is the result of luck and/or implementation defined (or not even defined) behaviour. detective columbo is just preparing the answer for you. in this case, the sign bit was 0. – Karoly Horvath Dec 27 '14 at 16:28

1 Answers1

11

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.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
  • 1
    I know that's what you meant, but to be clear: some implementations make `char` signed, others make it unsigned. On implementations where it is signed, `uint8_t` is not allowed to be a typedef for `char`. On implementations where it is unsigned, it is allowed. –  Dec 27 '14 at 13:45
  • `uint16_t` might also be `unsigned char` of course - although you're less likely to come across that in practice. – Alan Stokes Dec 27 '14 at 13:55
  • @hvd Thanks. Clarified. – Alan Stokes Dec 27 '14 at 13:56
  • @AlanStokes On a system where `uint16_t` is `unsigned char`, `uint8_t` would not exist and the OP's code would not compile :) – T.C. Dec 27 '14 at 17:52