Following my series from less known features of Modern C++.
constexpr
means constant at compile time. It was introduced in C++ 11 and later improved in C++14. It is generally used to save time and get the value at compile time.
Syntax
// Declaring variables
constexpr type name = value;
// Declaring functions
constexpr type func_name(...) {
// body
}
// Declaring classes and methods
class Foo {
int foo;
public:
constexpr Foo(int i) : foo(i){}
constexpr int GetSize() { return foo; }
}
Difference between const
and constexpr
?
-
const
can be used forruntime
andcompile time
butconstexpr
can only be used for compile time values. -
const
is just a constant whereasconstexpr
is a constant expression. -
const
can only be used for non-static function members but not for functions butconstexpr
can used anywhere but the return type should be a literal. - All
constexpr
values areconst
but not vice versa.
When to use constexpr
?
- Size for arrays
- Optimization
- Constant Expression
Rules
- Variables
- It must be Literal Type
- Initialized at compile time
- Functions
- Return type must be Literal
- Parameters must be Literal
- Must not contain
goto
- No Definition of non literal type
If you find some faults or some more content to add then please don't forget to comment.
Top comments (0)