I understand what const correctness means and my question is not about what const correctness is. So I am not expecting an explanation or C++-FAQ links for that.
My questions are:
- What are the semantic differences between
constin C andconstin C++? and - What is the reason for the difference?
Quotes from the respective standards which make the differences clear would be nice to have.
I regularly switch between C and C++ and I would like to know the important points that one should keep in mind while doing so.
I don't seem to remember the reason for these (special thanks if you can provide a reasoning) but from the top of my mind, I can remember:
- const variables in C++ have internal linkage by default, while in C they have default external linkage;
- const objects can be used as compile-time values in C++, but cannot be used as compile-time values in C;
- Pointers to string literals must be an
char const*in C++ but in C it can bechar*.
What am I missing?
const, so many programs were written assuming that"Hello, World"was of typechar[]when it is of typechar const[](and thus decays tochar const*. I think most compilers just didn't want to force people addingconsteverywhere (by default), but the-pedanticflag should report those violations.char*(4.2/2), which as far as I can see has been removed in C++11. So C++03 string literals were of type "array of n const char", but nevertheless could decay tochar*. Implementations don't have to warn about use of deprecated features, although gcc does by default since-Wwrite-stringsis on by default for C++.char[]in C.strchrand friends, while C doesn't. The reason is that C doesn't have function overloading and can't be bothered with defining two different functions, so instead it has a single const-incorrect function. Does that count as a difference between constants in C and C++?const, which is a different thing.constreally means "read-only", whereas a constant is a literal, and a constant expression is one that can be evaluated at compile time. (Although in C++, but not in C, aconstdeclaration can create a constant expression; for example, givenconst int x = 42;, the identifierxis a constant expression in C++.)