Literals are fixed values that are used directly in code. They do not need any computation during run-time. They come in various forms to represent different types of data efficiently. The most frequent literals are of numeric nature, but there are also literal operators for date, time and string types. A later concept will show how user-defined literal operators can be used.
Numeric literals include decimal, octal, hexadecimal, and binary representations. These basics were already covered in the numbers concept.
All representations like 23, 0x50f7ba11 and 0xba5eba11 are understood as int by the compiler.
The general int type is signed and (depending on the compiler and the system), often has a range of -2'147'483'648 to 2'147'483'647.
This is sufficient most of the time and you don't need to worry about the specific type.
Some use-cases demand larger ranges or very small memory footprints of programs. To be explicit one can directly state specific integer types with the numeric literal.
When negative numbers aren't needed, but the added range is desired the u or U suffix are used for unsigned integers.
For greater ranges L or even LL can be used for long and long long types.
The use of lower-case l is permitted, but it is easily confused with the number 1 and thus discouraged.
auto net_worth_christian_grey{2'500'000'000U}; // out of range for 32-bit integers
auto net_worth_carlisle_cullen{46'000'000'000LL}; // int and uint are not enough
Floating-point numbers usually resolve to double during compilation.
This is a good default case and use-cases with the narrower float type are less frequent than the unsigned example above.
auto light_year_in_m{9.46073e+15f}; // well in the range of float
auto earth_to_edge_comoving_distance_in_nm{4.32355e+32}; // needs double type for magnitude
auto eulers_number{2.718281828459045d}; // needs double type for precision
Other concepts already used character literals with single quotes like '}' or '@'.
In C++ char is limited to the first 128 [ascii character codes][ascii-code].
To use several ascii chars or extended ascii characters like β° or even unicode characters like ιΊ and αΊ other types are needed.
In previous concept string literals were introduced with double quotes: "δΈδ½γ©γγγζε³γ§γγγC++γ§γ".
The actual type of this Japanese phrase is const char (&)[46], a C-style string.
The use of string literals is not activated by default.
To use the string literal ""s or the string-view literal ""sv, the user has to specify their use by using the related namespace:
#include <string>
#include <string_view>
using namespace std::literals;
auto green_light{"무κΆν κ½ μ΄ νΌμ μ΅λλ€"};
// green_light type is const char (&)[36]
auto umbrella{"λ¬κ³ λ"s};
// umbrella type is std::basic_string<char>, the same as std::string
auto il_nam{"보λ κ²μ΄ νλ κ²λ³΄λ€ λ μ¬λ―Έμμ μκ° μμ§"sv};
// il_nam type is std::basic_string_view<char>
A string_view can be seen as a reference to a const string.