DEV Community

Swastik Baranwal
Swastik Baranwal

Posted on

4 2

Modern C++ : constexpr

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; }
}
Enter fullscreen mode Exit fullscreen mode

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.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay