I´ve found a comment of user R..:
C and C++ are not the same language. In particular, C
const
has nothing to do with C++const
.
I know, that one difference between the const
qualifier in C and the const
qualifier in C++ is its default linkage.
An object declared at namespace scope with const
qualifier in C++ has internal linkage, while in C an object with const
qualifier declared at global scope (without having a static
qualifier before const
) has external linkage.
But how else do they both differ between the languages of C and C++? I´ve thought both have the same kind of concept and purpose in both languages.
My Question:
- What is the difference between the const qualifier in C and the const qualifier in C++?
The answers to How does "const" differ in C and C++? do not point an exact difference between the languages of C and C++ in the context of the const
qualifier. Only what you can´t do or can do with it in a certain language.
Best Answer
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):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.