Reputation: 3356
Where could I find all the C++ decimal type indicator such as
long l = 0L;
I also know L U f d. Are there any others? Where can I find them all? How do I explicitly indicate an unsigned short?
Upvotes: 6
Views: 551
Reputation: 4369
This indicator you refer to is called a suffix.
For integer types, there are two types of suffixes:
u
or the character U
l
or the character L
or the long-long-suffix — the character sequence ll
or the character sequence LL
.For integer literals, you can combine these suffixes, such as ul
or ull
to achieve both "unsignednes" and "longness" in the same literal.
There are also suffixes for floating point types: one of f
, F
, l
, or L
double
f
or F
defines float
l
or L
defines long double
There are also user-defined literals, for which you can introduce user-defined suffixes.
As for your second question about unsigned short
: there is no explicit suffix for short
, so you will have to use static_cast
or C-style cast.
Another way to do it is to define a user-defined literal operator like this
unsigned short operator "" _ush(unsigned long long int a)
{
return static_cast<unsigned short>(a);
}
And then use it to define literals like this: unsigned short a = 123_ush;
I've checked that it works using this snippet:
#include <iostream>
#include <string>
#include <typeinfo>
unsigned short operator "" _ush(unsigned long long int a)
{
return static_cast<unsigned short>(a);
}
int main()
{
std::string name;
bool equal = typeid(decltype(123_ush)) == typeid(unsigned short); // check that literal is indeed unsigned short
std::cout << equal;
}
For more info on things mentioned in my answer, I would suggest checking out cppreference: Integer literals, Floating point literal, User-defined literal
Upvotes: 8
Reputation: 23701
You can find the full list of inbuilt literal affixes in lex.literal.
I would cite the full table but we don't have markdown support for this, so here is a list of suffixes:
Integer suffixes from lex.icon/2:
u
or U
l
or L
u
or U
and l
or L
ll
or LL
u
or U
and ll
or LL
Which exact type these denote depends on the magnitude of the literal value, but if you look into table 7, you will find that there are no suffixes that will give you an unsigned short
out of the box.
For completeness, here are the floating point suffixes from lex.fcon:
f
, l
, F
, L
.f
/F
indicate float
, l
/L
indicate long double
. No suffix means double
.
Upvotes: 0
Reputation: 234795
You can't. There is no such thing as an unsigned short
or short
literal in C++.
You need to use a static_cast
.
Reference: https://en.cppreference.com/w/cpp/language/integer_literal
Upvotes: 4
Reputation: 843
a short list is :
1.0 => double
1.0f => float
1 => int
1U => unsigned int
1L => long
1UL => unsigned long
1ULL => unsigned long long
1LL => long long
here is a good documentation for both prefixes and suffixes: https://www.geeksforgeeks.org/integer-literal-in-c-cpp-prefixes-suffixes/
Upvotes: 1