HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

What is an unsigned char?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
charwhatunsigned

Problem

In C/C++, what is an unsigned char used for? How is it different from a regular char?

Solution

In C++, there are three distinct character types:

  • char



  • signed char



  • unsigned char



  1. char



If you are using character types for text, use the unqualified char:

  • it is the type of character literals like 'a' or '0' (in C++ only, in C their type is int)



  • it is the type that makes up C strings like "abcde"



It also works out as a number value, but it is unspecified whether that value is treated as signed or unsigned. Beware character comparisons through inequalities - although if you limit yourself to ASCII (0-127) you're just about safe.
  1. signed char/ 3. unsigned char



If you are using character types as numbers, use:

  • signed char, which gives you at least the -127 to 127 range. (-128 to 127 is common)



  • unsigned char, which gives you at least the 0 to 255 range. This might be useful for displaying an octet e.g. as hex value.



"At least", because the C++ standard only gives the minimum range of values that each numeric type is required to cover. sizeof (char) is required to be 1 (i.e. one byte), but a byte could in theory be for example 32 bits. sizeof would still be report its size as 1 - meaning that you could have sizeof (char) == sizeof (long) == 1.

Context

Stack Overflow Q#75191, score: 627

Revisions (0)

No revisions yet.