Introduction
Consider the following,
#include <iostream>
#include <typeinfo>
int main() {
auto y {12.4};
std::cout << "The type of y is: " << typeid(y).name();
}
// Output
The type of y is: d
Woah!
Even though we didn’t specify the type of the variable, the compiler was able to deduce it.
When auto is used, the compiler deduces the variable’s type from the initializer. Since literals already have types, this instruction succeeded.
How is this possible?
This is possible since literals have a type. The compiler is smart enough to deduce the type based of the literals in the initializer list.
Use literal suffixes to change the type
We can be explicit about the type e.g. hp = 100u;
This is equivalent to unsigned int hp = 100;
auto very_large_number { 9999LL ); deduces to a long long.
String suffixes
auto name { "Jerry "}; evaluates to a C-style string, however using string suffixes we can change this.
using namespace std::string_view_literals;
auto a { "Mango" }; // string literal
auto b { "Cherry"s }; // std::string
auto c { "Banana"sv }; // std::string_view
Literal suffixes can apply to other types as well.
| Data type | Suffix | Meaning |
|---|---|---|
| integral | u or U | unsigned int |
| integral | l or L | long |
| integral | ul, uL, Ul, UL, lu, lU, Lu, LU | unsigned long |
| integral | ll or LL | long long |
| integral | ull, uLL, Ull, ULL, llu, llU, LLu, LLU | unsigned long long |
| integral | z or Z | The signed version of std::size_t (C++23) |
| integral | uz, uZ, Uz, UZ, zu, zU, Zu, ZU | std::size_t (C++23) |
| floating point | f or F | float |
| floating point | l or L | long double |
| string | s | std::string |
| string | sv | std::string_view |