What is the difference between the const qualifier in C and the const qualifier in C++?
The most important difference is that in C++ a
const
variable is a constant expression (even prior the introduction of C++11constexpr
), but aconst
variable in C is not.Meaning that C++ allows you to do things like
const size_t n = 1; static int array[n];
but C does not allow that, supposedly for historical reasons.In C++,
const
plays part in determining linkage. This is different between C++ versions. According to cppreference.com (emphasis mine):Any of the following names declared at namespace scope have internal linkage:
- non-volatile non-template (since C++14) non-inline (since C++17) non-exported (since C++20) const-qualified variables (including constexpr) that aren't declared extern and aren't previously declared to have external linkage;
Whereas in C,
const
does not play part in determining linkage at all - only declaration scope and storage class specifiers matter.In C++, you can
const
qualify member functions. This isn't possible in C since it doesn't have syntax support for member functions.C allows
const
-qualified variables to be declared without an initializer. In C, we can writeconst int x;
without initializers, but C++ does not allow that. At a glance, this may seem like a senseless language bug in C, but the rationale is that computers have read-only hardware registers with values set by hardware, not software. Meaning that C remains suitable for hardware-related programming.