What is the difference between the const qualifier in C and the const qualifier in C++?

RobertS supports Monica Cellio :

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.

Lundin :
  • The most important difference is that in C++ a const variable is a constant expression (even prior the introduction of C++11 constexpr), but a const 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 write const 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29506&siteId=1