Question

I can specify an integer literal of type unsigned long as follows:

const unsigned long example = 9UL;

How do I do likewise for an unsigned char?

const unsigned char example = 9U?;

This is needed to avoid compiler warning:

unsigned char example2 = 0;
...
min(9U?, example2);

I'm hoping to avoid the verbose workaround I currently have and not have 'unsigned char' appear in the line calling min without declaring 9 in a variable on a separate line:

min(static_cast<unsigned char>(9), example2);
Was it helpful?

Solution

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.

OTHER TIPS

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
}

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.

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.

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);

Simply const unsigned char example = 0; will do fine.

I suppose '\0' would be a char literal with the value 0, but I don't see the point either.

There is no suffix for unsigned char types. Integer constants are either int or long (signed or unsigned) and in C99 long long. You can use the plain 'U' suffix without worry as long as the value is within the valid range of unsigned chars.

The question was how to "specify an integer 'literal' of type unsigned char in C++?". Not how to declare an identifier.

You use the escape backslash and octal digits in apostrophes. (eg. '\177')

The octal value is always taken to be unsigned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top