views:

492

answers:

6

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);
+4  A: 

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

Kyle Lutz
+1  A: 

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

Axel Gneiting
This is not unsigned char, but signed char.
WilliamKF
@WilliamKF: the type of `'\0'` in C++ is neither `signed char` not `unsigned char`, it is `char` as Axel says. `char` is unlike other integral types: `signed int` and `int` are the same type, but `signed char` and `char` are not.
Steve Jessop
A: 

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.

+4  A: 

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.

Michael Burr
+2  A: 

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);
Whisty
+3  A: 

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.

janm
I think you are the only one that decrypted his pretty secret question correctly. Firstly, i didn't figure out either what he really wanted to ask.
Johannes Schaub - litb
Right, that is my current work around, with this question I was hoping to avoid the cast, but it sounds like the answer is there is no literal that will allow me to avoid the cast.
WilliamKF