221

I wrote a simple program that sets a value to a variable and then prints it, but it is not working as expected. My program has only two lines of code:

uint8_t a = 5;

cout << "value is " << a << endl;

The output of this program is value is , i.e., it prints blank for a.

When I change uint8_t to uint16_t, the above code works like a charm.

I use Ubuntu 12.04 (Precise Pangolin), 64-bit, and my compiler version is:

gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
3

8 Answers 8

233

It doesn't really print a blank, but most probably the ASCII character with value 5, which is non-printable (or invisible). There's a number of invisible ASCII character codes, most of them below value 32, which is the blank actually.

You have to convert a to unsigned int to output the numeric value, since ostream& operator<<(ostream&, unsigned char) tries to output the visible character value.

uint8_t a = 5;

cout << "value is " << unsigned(a) << endl;
26
  • 30
    Since C style casts are frowned upon, wouldn't it be better to do a static_cast? Oct 24, 2013 at 12:09
  • 47
    It should be converted to int. A cast is one way to do that, but not the only way. +aa also works. Oct 24, 2013 at 14:07
  • 7
    isn't int(var) and (int)var actually the same thing?
    – paulm
    Feb 17, 2014 at 23:18
  • 9
    See the linked question using type(var) is the same as (type)var its the same as the C cast - try it out with const etc, it removes it!
    – paulm
    Feb 17, 2014 at 23:27
  • 16
    The response "No. c-style casts are discouraged for c++ for a number of reasons." to "isn't int(var) and (int)var actually the same thing?" sure makes it seem as if you didn't realise int(var) and (int)var have exactly the same meaning. int(var) is discouraged in exactly those cases where (int)var is, for exactly the same reasons, because it means exactly the same thing. (I can understand why you'd go for it here anyway, though, so I'm not saying you need to use static_cast. I just think the comment trail here got a bit unnecessarily confusing.)
    – user743382
    Feb 25, 2015 at 16:01
79

Adding a unary + operator before the variable of any primitive data type will yield a printable numerical value instead of an ASCII character (in case of char type).

uint8_t a = 5;
cout << "value is " << +a << endl; // value is 5

This works because +a result in a being promoted to int.

12
  • 2
    That's nice, but why doesn't c++ treat uint8_t as unsigned char which would be numerical values?
    – R1S8K
    May 25, 2019 at 21:35
  • 1
    @R1S8K this is because while uint8_t is just a type def of unsigned char, unsigned char itself is handled by ostream just like char and prints its ASCII value.
    – Harsh
    May 16, 2020 at 8:55
  • @Harsh Thanks man ! so it's a type def of unsigned char that explains a lot. So the only integer is int, right ?
    – R1S8K
    May 17, 2020 at 15:03
  • @R1S8K Well, the smallest integer type would be short int which takes up 2 bytes. There are a few other variations of the integer type as well.
    – Harsh
    May 17, 2020 at 17:09
  • @Harsh Also I think when programming and declaring variables, it doesn't matter if I declare a variable that would deal only with small numbers not exceeding like 250 with a big register size like long or int because the compiler would optimize the use of RAM or flash according to what fills that register, am I right ?
    – R1S8K
    May 19, 2020 at 8:58
61

uint8_t will most likely be a typedef for unsigned char. The ostream class has a special overload for unsigned char, i.e. it prints the character with the number 5, which is non-printable, hence the empty space.

1
  • 34
    I wish the standard really treated std::uint8_t as a separate type and not just a friggin' typedef. There is no sane reason to apply character-semantics to these types when used in conjunction with stream objects.
    – antred
    Jul 31, 2015 at 14:19
21
  • Making use of ADL (Argument-dependent name lookup):

    #include <cstdint>
    #include <iostream>
    #include <typeinfo>
    
    namespace numerical_chars {
    inline std::ostream &operator<<(std::ostream &os, char c) {
        return std::is_signed<char>::value ? os << static_cast<int>(c)
                                           : os << static_cast<unsigned int>(c);
    }
    
    inline std::ostream &operator<<(std::ostream &os, signed char c) {
        return os << static_cast<int>(c);
    }
    
    inline std::ostream &operator<<(std::ostream &os, unsigned char c) {
        return os << static_cast<unsigned int>(c);
    }
    }
    
    int main() {
        using namespace std;
    
        uint8_t i = 42;
    
        {
            cout << i << endl;
        }
    
        {
            using namespace numerical_chars;
            cout << i << endl;
        }
    }
    

    output:

    *
    42
    
  • A custom stream manipulator would also be possible.

  • The unary plus operator is a neat idiom too (cout << +i << endl).
17
  • 9
    Isn't KISS still a valid paradigm?? Jan 30, 2014 at 0:58
  • 1
    @πάνταῥεῖ of course, but don't forget: Everything Should Be Made as Simple as Possible, But Not Simpler
    – oblitum
    Jan 30, 2014 at 1:22
  • 4
    @πάνταῥεῖ ok, keep doing tons of c style casts in c++ code then, anyone is free to be productive the way it is, in the environment that he/she fits the most.
    – oblitum
    Jan 30, 2014 at 2:13
  • 5
    @πάνταῥεῖ seriously? functional style cast, also, is just c style casting. changing one from the other doesn't help in anything in leaving the realm of C, check: stackoverflow.com/a/4775807/1000282. pete-becker commented this on your answer too, but you seem to have missed his last comment.
    – oblitum
    Jan 30, 2014 at 2:58
  • 6
    This solution is very elegant & effective, because it works with templates. In facts, that's the only solution I've spotted that works for me. One caveat though, the first function has a bug, because 'os' is bound to a single type, and therefore, either the signed or the unsigned value will be sent to the wrong version of operator<<(). The fix is simple enough: return std::is_signed<char>::value ? os << static_cast<int>(c) : os << static_cast<unsigned int>(c);
    – Georges
    Jun 24, 2017 at 21:21
20

It's because the output operator treats the uint8_t like a char (uint8_t is usually just an alias for unsigned char), so it prints the character with the ASCII code (which is the most common character encoding system) 5.

See e.g. this reference.

3
  • Why? the C compiler treats it as a number. I think C++ is different at this point.
    – R1S8K
    May 25, 2019 at 21:36
  • @PerchEagle If you read the linked reference you will see that the operator is overloaded for both signed and unsigned characters (beyond plain char which in C++ is really a third separate type). So if uint8_t is an alias for unsigned char (very likely) that's what will be used. May 25, 2019 at 22:05
  • Could you check my answer on this thread and tell me if my answer is right or not? stackoverflow.com/questions/15585267/…, my answer is before the last one. Thank you so much.
    – R1S8K
    May 26, 2019 at 12:00
8

cout is treating aa as char of ASCII value 5 which is an unprintable character, try typecasting to int before printing.

1
  • variable size will increase to 4 byte from 1 byte. I want a 1 byte variable. any help?
    – Sadegh J
    May 26, 2021 at 14:07
7

The operator<<() overload between std::ostream and char is a non-member function. You can explicitly use the member function to treat a char (or a uint8_t) as an int.

#include <iostream>
#include <cstddef>

int main()
{
   uint8_t aa=5;

   std::cout << "value is ";
   std::cout.operator<<(aa);
   std::cout << std::endl;

   return 0;
}

Output:

value is 5
3

As others said before the problem occurs because standard stream treats signed char and unsigned char as single characters and not as numbers.

Here is my solution with minimal code changes:

uint8_t aa = 5;

cout << "value is " << aa + 0 << endl;

Adding "+0" is safe with any number including floating point.

For integer types it will change type of result to int if sizeof(aa) < sizeof(int). And it will not change type if sizeof(aa) >= sizeof(int).

This solution is also good for preparing int8_t to be printed to stream while some other solutions are not so good:

int8_t aa = -120;

cout << "value is " << aa + 0 << endl;
cout << "bad value is " << unsigned(aa) << endl;

Output:

value is -120
bad value is 4294967176

P.S. Solution with ADL given by pepper_chico and πάντα ῥεῖ is really beautiful.

2
  • variable size will increase to 4 byte from 1 byte. I want a 1 byte variable. any help?
    – Sadegh J
    May 26, 2021 at 14:14
  • Ingenious, I have a templated << operator for uint8_t and float, and this one works perfectly
    – trexxet
    Mar 27, 2022 at 13:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.