I have recently started using more C++11 features in my code and I have been wondering if the placement of the constexpr
keyword makes difference whether it is before or after the constant's type.
Style 1:
constexpr int FOO = 1;
constexpr auto BAR = "bar";
Style 2:
int constexpr FOO = 1;
auto constexpr BAR = "bar";
Style 2 is the way I prefer to place the const
keyword and placing constexpr
the same way would bring some consistency to the code. However, is that considered bad practice or is there something else wrong with style 2 because I don't really see anyone writing it like that.
It's a specifier, like long
, short
, unsigned
, etc. They can all be moved around. For example, the following are two equivalent and valid declarations:
int long const long unsigned constexpr foo = 5;
constexpr const unsigned long long int foo = 5;
By convention, though, constexpr
would appear before the type name. It can confuse others if you put it after, but it is technically valid. Since constexpr
serves a different purpose than const
, I don't see the same benefit in putting it to the right. For example, you can't do int constexpr * constexpr foo
. In fact, int constexpr * foo
will not allow you to reassign foo
, rather than apply to what foo
points to, so putting it to the right can be misleading if you expect the same kind of semantics as const
.
To summarize:
int constexpr foo = 0; // valid
int constexpr * constexpr foo = nullptr; // invalid
int* constexpr foo = nullptr; // invalid
int constexpr * foo = nullptr; // valid
constexpr int* foo = nullptr; // valid and same as previous
msdn defines the syntax as:
constexpr literal-type identifier = constant-expression;constexpr literal-type identifier { constant-expression };constexpr literal-type identifier(params );constexpr ctor (params);
Which says that you should use it on the left.
Edit:
New specifier The keyword constexpr is a declaration specifier; modify the grammar in [ISO03, §7.1] as follows:
1 The specifiers that can be used in a declaration are decl-specifier:
storage-class-specifier
type-specifier
function-specifier
friend
typedef
constexpr
An explanation is given for this specifiers here.
To sum up @chris' answer is right :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With