cpprussia C++ Russia 2020 Msc (29.06.2020 — 02.07.2020)

How to declare a constant in C++?


In this talk, we will understand how to choose static, inline and constexpr specifiers when declaring a constant. We will compare different ways to declare string constants. As a result, we will come up with universal recommendations.

<p>The amazing thing about C++ is that the simplest things can be extremely confusing and complicated. It seems to be easy to declare a constant.</p> <p>We need to choose the linkage and storage duration that is suitable for us, to determine the visibility of constant and what translation unit it will be presented in. Then we need to choose an appropriate definition: global variable, local variable, class static data member. Then we need to pick an appropriate combination of static, inline and constexpr specifiers. We may also make the variable a template or a reference. If we are talking about a string, we need to choose the right type: const char*, char[], std::string, std::string_view.</p> <p>If these things are obvious for you — congratulations! This is impressive. If this information blows your mind, let’s deal with this.</p> <p>The talk assumes an understanding of linkage and storage duration, declaration and definition, and static, inline and constexpr specifiers. These concepts are explained in Mikhail’s previous talk "Specifiers, qualifiers and templates" from C++ Russia Piter 2019.</p>