Sujet : Re: constexpr keyword is unnecessary
De : Keith.S.Thompson+u (at) *nospam* gmail.com (Keith Thompson)
Groupes : comp.lang.cDate : 19. Oct 2024, 00:54:57
Autres entêtes
Organisation : None to speak of
Message-ID : <877ca5q84u.fsf@nosuchdomain.example.com>
References : 1
User-Agent : Gnus/5.13 (Gnus v5.13)
Thiago Adams <
thiago.adams@gmail.com> writes:
I think constexpr keyword is unnecessary.
Sure, most language features are strictly unnecessary.
Anything you do with it could/should be done with const.
No, absolutely not.
Keep in mind that "const" doesn't mean "constant".
In C, "constant" means (roughly) evaluable at compile time. (And as a
noun, it refers to what many other languages call "literals".)
The "const" keyword means "read-only"; the object it applies to cannot
be modified after it's initialized. The fact that the spelling of
the "const" keyword is derived from the word "constant" has caused a
great deal of confusion. Spelling it as "readonly" rather than "const"
would have avoided most of that confusion.
As of C11, the "const" keyword *never* makes an identifer usable in a
context that requires a constant expression. Given the following:
const int foo = <initializer>;
foo is treated the same way whether the initializer is constant
(e.g., 42) or not (e.g., rand()).
It's unfortunate that C11 doesn't provide a convenient way to define an
identifier as a constant expression of any arbitrary type. Adding
constexpr in C23 addresses that problem.
C++ made what was, in my opinion, an unfortunate decision. Given:
const int foo = 42;
const int bar = rand();
the name foo is a constant expression, but bar is not. This feature
(hack, IMHO) was added to C++ at a time that constexpr did not yet
exist.
So in C11, it's easy to explain what "const" means, but in C++ it's more
difficult because of that special-case rule.
"const" and "constexpr" do very different things. Conflating those into
a single keyword is not helpful. It might make the language easier to
use in some cases, but it makes it harder to explain. Spelling "const"
as "readonly" would have been an improvement, but it's far too late to
do that.
-- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.comvoid Void(void) { Void(); } /* The recursive call of the void */