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?
-
constcan be used forruntimeandcompile timebutconstexprcan only be used for compile time values. -
constis just a constant whereasconstexpris a constant expression. -
constcan only be used for non-static function members but not for functions butconstexprcan used anywhere but the return type should be a literal. - All
constexprvalues areconstbut 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)