constexpr position in variable declaration
Solution 1:
constexpr
is a decl-specifier, as are int
and const
.
Other decl-specifiers are for example thread_local
, mutable
, extern
, virtual
, extern
, friend
, typedef
, consteval
, constinit
and inline
, as well as other type-specifiers such as volatile
, long
, double
, auto
, signed
, decltype(...)
, names of types, types introduced by class
, enum
, union
, struct
, etc.
A sequence of decl-specifiers makes up the decl-specifier-seq of a declaration. Following the decl-specifier-seq is typically a list of declarators, separated by commas, which declare the entities with the given decl-specifiers. (But for example the *
in int* s;
is part of the declarator, not the specifier sequence.)
I don't think there is any instance in the standard where the order of the decl-specifier-seq has any relevance. For example the following compiles without issue and should have the same meaning as in the conventional order of specifiers:
struct { double volatile mutable long x = 1; } typedef const S;
inline S thread_local constexpr *s = {};
See the post-C++20 draft of the C++ standard, section [dcl.spec]. It specifies the grammar of the decl-specifier-seq and the individual specifiers. In the rest of the section certain combinations of specifiers are forbidden, but their order is not mentioned.
So
int constexpr x;
and
constexpr int x;
are equivalent.
But what is not possible is e.g.
int* constexpr x;
The constexpr
would here be part of the declarator. It could be written as
int constexpr* x;
though.
I suppose that makes putting constexpr
as a rule after the type specifier confusing. It is the same rule as for const
, but constexpr
should only ever apply to the whole declaration, not to the type or a subtype.
I think it is likely that the code analysis tool is simply complaining about the style rather than the functionality of the syntax. It is unusual to place constexpr
behind the type specifiers, as it is unusual to put e.g. const
between the two long
in long long
, and if the specifiers are in uncommon order it may become hard to read the code.