What's the Difference Between Constexpr and Const?
What's the Difference Between Constexpr and Const? When Can I Use Only One of Them? When Can I Use Both and How Should I Choose One? 6 10 Answers Basic Meaning...
What's the difference between constexpr and const?
- When can I use only one of them?
- When can I use both and how should I choose one?
10 Answers
Must Read
Basic meaning and syntax
Both keywords can be used in the declaration of objects as well as functions. The basic difference when applied to objects is this:
constdeclares an object as constant. This implies a guarantee that once initialized, the value of that object won't change, and the compiler can make use of this fact for optimizations. It also helps prevent the programmer from writing code that modifies objects that were not meant to be modified after initialization.constexprdeclares an object as fit for use in what the Standard calls constant expressions. But note thatconstexpris not the only way to do this.
When applied to functions the basic difference is this:
constcan only be used for non-static member functions, not functions in general. It gives a guarantee that the member function does not modify any of the non-static data members (except for mutable data members, which can be modified anyway).constexprcan be used with both member and non-member functions, as well as constructors. It declares the function fit for use in constant expressions. The compiler will only accept it if the function meets certain criteria (7.1.5/3,4), most importantly (†):- The function body must be non-virtual and extremely simple: Apart from typedefs and static asserts, only a single
returnstatement is allowed. In the case of a constructor, only an initialization list, typedefs, and static assert are allowed. (= defaultand= deleteare allowed, too, though.) - As of C++14, the rules are more relaxed, what is allowed since then inside a constexpr function:
asmdeclaration, agotostatement, a statement with a label other thancaseanddefault, try-block, the definition of a variable of non-literal type, definition of a variable of static or thread storage duration, the definition of a variable for which no initialization is performed. - The arguments and the return type must be literal types (i.e., generally speaking, very simple types, typically scalars or aggregates)
- The function body must be non-virtual and extremely simple: Apart from typedefs and static asserts, only a single