Back
Close

7 Features of C++17 that will simplify your code

fenbf
216.7K views

Inline variables

With Non-Static Data Member Initialization (see my post about it here), we can now declare and initialize member variables in one place. Still, with static variables (or const static) you usually need to define it in some cpp file.

C++11 and constexpr keyword allow you to declare and define static variables in one place, but it's limited to constexpr'essions only. I've even asked the question: c++ - What's the difference between static constexpr and static inline variables in C++17? - Stack Overflow - to make it a bit clear.

Ok, but what's the deal with this feature:

Previously only methods/functions could be specified as inline, but now you can do the same with variables, inside a header file.

A variable declared inline has the same semantics as a function declared inline: it can be defined, identically, in multiple translation units, must be defined in every translation unit in which it is used, and the behavior of the program is as if there was exactly one variable.

struct MyClass
{
    static const int sValue;
};

inline int const MyClass::sValue = 777;

Or even:

struct MyClass
{
    inline static const int sValue = 777;
};

Also, note that constexpr variables are inline implicitly, so there's no need to use constexpr inline myVar = 10;.

Why can it simplify the code?

For example, a lot of header only libraries can limit the number of hacks (like using inline functions or templates) and just use inline variables.

The advantage over constexpr is that your initialization expression doesn't have to be constexpr.

More info in:

GCC: 7.0, Clang: 3.9, MSVC: in VS 2017.3.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants