The constexpr keyword

 

The keyword constexpr is used to show that a constant is resolved at compile time. This is a new keyword introduced with C++11.

Both constexpr and const are used to show that something is constant and the difference is that a constexpr value must be resolved at compile time  whereas a const can be resolved at run time or at compile time.

In most cases there is no real difference between a compile time or a run time constant but in some cases must the constant be defined at compile time. One example is creating fixed size arrays where the size must be a constant defined at compile time:

constexpr can also be used for function calls

However, a constexpr function must only consist of a single return statement, only call constexpr functions and only access constexpr global/member variables.

The purpose of constexpr is to replace macros and hard coded literal values without sacrificing performance or type safety.

Facebookgoogle_pluslinkedinmail

The const keyword

The const keyword is used to show both other developers and the compiler that an object is constant and its contents cannot be changed. If you anyway try to change the contents of a const object will generate an error already at compile time. It is a good practice to add the const keyword to a parameter, a members or a method to show that the value is not going to be changed. This can both make the intent of the code more clear to the user, and can make the code faster since the compiler can make certain optimizations knowing that the object is not going to change its value.

The difference between the const keyword and the constexpr keyword is that the value of a constexpr constant must be resolved at compile time whereas the value of a const constant can be resolved at run time (or at compile time).

The const keyword can be used in the following contexts:

Const class

An object can be made constant at creation by declaring the object as const:

Any attempt to change the contents of the object christmasDay will result in a compiler error:

 

Const member functions

Adding the const keyword to a member function (added at the end of the function declaration, after the parameters) states that this method will not change the state of the object.

The const keyword after the declaration of the method getYear() shows that calling this method will not change any members of the object. This also means that we are allowed to call this method even if the object is const.

 

Const parameters

Parameters to functions can also be declared as const. There are two positions where the const keyword can be added.

 

 

 

Facebookgoogle_pluslinkedinmail