Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do fixed-width integers print out chars instead of ints?

Given the following code.

#include <cstdint>
#include <iostream>
#include <limits>

int main()
{
    int8_t x = 5;
    std::cout << x << '\n';

    int y = 5;
    std::cout << y;

    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cin.get();

    return 0;
}

My output is a three-leaf clover and 5. If fixed-width integers are integers, why are they outputting their number's ASCII character symbol?

Edit: just found out this behavior only happens for 8-bit fixed-width integers? Is this compiler behavior?

like image 441
Wandering Fool Avatar asked Dec 09 '22 03:12

Wandering Fool


1 Answers

Well, they are integers in the sense that you can do 8 bit integer arithmetic with them.

But apparently on your system, int8_t is implemented as a typedef to signed char. This is completely legal since signed chars are also integers, but gives unexpected results since the operator<< for signed chars prints their character symbol and not their numeric value. Anything else would just be weird if someone tried to print an signed char.

If you want to see the numeric value of your int8_t, just cast to int before printing.

like image 200
Baum mit Augen Avatar answered Mar 02 '23 18:03

Baum mit Augen