const vs constexpr in C++

CMP
4 min readSep 15, 2023

Both const and constexpr are keywords used to specify that a value cannot be modified, but they have some differences in functionality and use cases.

What is const?

const is a fundamental keyword in C++ used for defining constant variables, meaning the value of the variable cannot change. Look at the following simple example of this concept:

int main() {
const int a = 0;
a = 5; // error

return 0;
}

In addition to constant variables, const can be used for member functions. Look at the following class:

class MyClass {
public:
void SetValue(int newValue);
int GetValue() const;

private:
int m_value;
}

void MyClass::SetValue(int newValue) {
m_value = newValue;
}

int MyClass::GetValue() const {
return m_value;
}

In this example, GetValue() is defined as const, which promises that m_value will remain unmodified within the GetValue() function. In contrast, SetValue(int newValue) is not const, so m_value is allowed to be modified.

Consider the following modification:

void MyClass::SetValue(int newValue) const {
m_value = newValue; // error
}

Here, SetValue(int newValue) is defined as const, which results in an error because an object’s state cannot be modified within its own const member functions.

Another important feature of const is that both const and non-const member functions can be called by non-const

--

--

CMP

Software engineer specializing in operating systems, navigating the intracicies of the C++ language and systems programming.