Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where could I find all the C++ decimal type indicator?

Tags:

c++

keyword

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?

like image 984
Zhang Avatar asked Apr 09 '19 08:04

Zhang


3 Answers

This indicator you refer to is called a suffix.

For integer types, there are two types of suffixes:

  1. unsigned-suffix — the character u or the character U
  2. long-suffix — the character 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

  1. Without suffix a literal defines double
  2. f or F defines float
  3. 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

like image 118
JustSomeGuy Avatar answered Oct 13 '22 00:10

JustSomeGuy


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

like image 24
Bathsheba Avatar answered Oct 13 '22 01:10

Bathsheba


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/

like image 21
yekanchi Avatar answered Oct 13 '22 00:10

yekanchi