Specifying unsigned char storage for integer numerals

Viewed 171

In terms of modern C++, is it possible to specify storage of a integer numeral to a char?

I am looking to write auto var = 255; to initialize var as unsigned char type

It is possible to specify other types of storage:

auto var_ulong = 255ul;
auto var_float = 255.f;

However, not short or char? Surely I am missing something...

1 Answers

There is no standard integer literal to do what you want, but you can add your own user- defined literal if you plan to do this a lot:

namespace foo {

// constexpr pre C++20
//  |
//  V 
consteval unsigned char operator"" _uchar(unsigned long long x) {
    return static_cast<unsigned char>(x);
}

}
using namespace foo;
auto var_uchar = 255_uchar;

Just be aware that normal integer promotion will still be in effect, so below, you'll get an int:

auto var_int = 55_uchar + 10_uchar;
Related