C++ differences between const and constexpr

Some of the C++ differences between const and constexpr are discussed here.

The two keywords ‘const’ and ‘constexpr’ qualify a variable or a function as constant. They adhere to the strict law that something constant must remain constant throughout its lifetime and any compromise on the part of the variable or function is not allowed. However, there are some variations on how these two works and no doubt we can find their differences even in some of our programs. Here I want to explicitly point out some of their differences.

Link :constexpr qualifier

First

const can be used as a qualifier in the function parameter but constexpr cannot.

int func(const int ii) { return ii; }

int func(constexpr int ii) { return ii; } //error!

const and constexpr function

The ‘const’ function can be only part of a class member function, but constexpr can be non-member function. However, note the constexpr function cannot be declared outside a class, for it to be valid it should be defined.

Link :C++11 constexpr function

class A
{

public:
  constexpr int func123(); //work fine
}

int func() const //error!! should be part of class member function
{ } 

constexpr string tool(); //error!! just declaration not allowed

const int work(int arg) //work fine!! 
{ return arg*arg; } 


Leave a Reply

Your email address will not be published. Required fields are marked *