How to write an unsigned short int literal?

at least in Visual Studio (at least 2013 and newer) you can write

23ui16

for get an constant of type unsigned short.

see definitions of INT8_MIN, INT8_MAX, INT16_MIN, INT16_MAX, etc. macros in stdint.h

I don't know at the moment whether this is part of the standard C/C++


You can't. Numeric literals cannot have short or unsigned short type.

Of course in order to assign to bar, the value of the literal is implicitly converted to unsigned short. In your first sample code, you could make that conversion explicit with a cast, but I think it's pretty obvious already what conversion will take place. Casting is potentially worse, since with some compilers it will quell any warnings that would be issued if the literal value is outside the range of an unsigned short. Then again, if you want to use such a value for a good reason, then quelling the warnings is good.

In the example in your edit, where it happens to be a template function rather than an overloaded function, you do have an alternative to a cast: do_something<unsigned short>(23). With an overloaded function, you could still avoid a cast with:

void (*f)(unsigned short) = &do_something;
f(23);

... but I don't advise it. If nothing else, this only works if the unsigned short version actually exists, whereas a call with the cast performs the usual overload resolution to find the most compatible version available.


unsigned short bar = (unsigned short) 23;

or in new speak....

unsigned short bar = static_cast<unsigned short>(23);

Tags:

C++

Types