How do I specify an integer literal of type unsigned char in C++?

Solution 1:

C++11 introduced user defined literals. It can be used like this:

inline constexpr unsigned char operator "" _uchar( unsigned long long arg ) noexcept
{
    return static_cast< unsigned char >( arg );
}

unsigned char answer()
{
    return 42;
}

int main()
{
    std::cout << std::min( 42, answer() );        // Compile time error!
    std::cout << std::min( 42_uchar, answer() );  // OK
}

Solution 2:

C provides no standard way to designate an integer constant with width less that of type int.

However, stdint.h does provide the UINT8_C() macro to do something that's pretty much as close to what you're looking for as you'll get in C.

But most people just use either no suffix (to get an int constant) or a U suffix (to get an unsigned int constant). They work fine for char-sized values, and that's pretty much all you'll get from the stdint.h macro anyway.

Solution 3:

You can cast the constant. For example:

min(static_cast<unsigned char>(9), example2);

You can also use the constructor syntax:

typedef unsigned char uchar;
min(uchar(9), example2);

The typedef isn't required on all compilers.

Solution 4:

If you are using Visual C++ and have no need for interoperability between compilers, you can use the ui8 suffix on a number to make it into an unsigned 8-bit constant.

min(9ui8, example2);

You can't do this with actual char constants like '9' though.

Solution 5:

Assuming that you are using std::min what you actually should do is explicitly specify what type min should be using as such

unsigned char example2 = 0;
min<unsigned char>(9, example2);