loading...

Modern C++ : constexpr

delta456 profile image Swastik Baranwal ・1 min read

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 for runtime and compile time but constexpr can only be used for compile time values.
  • const is just a constant whereas constexpr is a constant expression.
  • const can only be used for non-static function members but not for functions but constexpr can used anywhere but the return type should be a literal.
  • All constexpr values are const but not vice versa.

When to use constexpr?

  • Size for arrays
  • Optimization
  • Constant Expression

Rules

  1. Variables
  • It must be Literal Type
  • Initialized at compile time
  1. 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.

Discussion

markdown guide