Yves
Yves

Reputation: 12371

The best way to define a const variable

I'm coding with C++ and I want to know the best way to define a const variable.

As my understanding, if I want to define a const variable in cpp file, we can code like this before: const static int LEN = 5; And now C++ suggests us using anonymous namespace: namespace { const int LEN = 5; }

I don't know how to define a const variable in header file properly.

I've seen some codes in some header files as below:

const int LEN = 5;

So is this the best way? Why don't we code const static int LEN = 5; in header file?

Upvotes: 0

Views: 1162

Answers (1)

user2486888
user2486888

Reputation:

I'm coding with C++ and I want to know the best way to define a const variable.

There is no "best way". It depends.

BTW, ever heard of constexpr?

As my understanding, if I want to define a const variable in cpp file, we can code like this before: const static int LEN = 5;

Yes, we can.

Note that things in namespace scope declared with static keyword has internal linkage.

Also note that I am not calling LEN a "static variable".

And now C++ suggests us using anonymous namespace: namespace { const int LEN = 5; }

Everything declared in anonymous namespace has internal linkage. But I don't think C++ itself makes any suggestion.

I've seen some codes in some header files as below:

const int LEN = 5;

C++ has a special provision that makes namespace-scoped const-qualified variables have internal linkage by default, even without static specifier.

See: https://en.cppreference.com/w/cpp/language/storage_duration#Linkage

Note that it is different from C.

Also note that it does not mean "const includes static". Thinking in this way is confusing.

Why don't we code const static int LEN = 5; in header file?

Actually, we can. It may even be beneficial due to non-technical reasons. If you think that your audience who reads your code does not know that special provision, a static specifier will make clear to your audience that the variable has internal linkage.

Upvotes: 1

Related Questions