#029 – Using literal suffixes

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 typeSuffixMeaning
integralu or Uunsigned int
integrall or Llong
integralul, uL, Ul, UL, lu, lU, Lu, LUunsigned long
integralll or LLlong long
integralull, uLL, Ull, ULL, llu, llU, LLu, LLUunsigned long long
integralz or ZThe signed version of std::size_t (C++23)
integraluz, uZ, Uz, UZ, zu, zU, Zu, ZUstd::size_t (C++23)
floating pointf or Ffloat
floating pointl or Llong double
stringsstd::string
stringsvstd::string_view

Leave a Reply

Your email address will not be published. Required fields are marked *