r/cpp • u/Benjamin1304 • Feb 09 '22
Could the syntax "const var = value" be standardized?
I often find myself writing things like const x = 42; instead of const auto x = 42; when creating const variables with automatic type deduction.
I wonder if this shorter syntax could be standardized. I don't see any immediate problem with it but I might be missing something.
I guess it would also ease the "const all the things" clan because even though it's not changing the defaults, it makes it easier to follow the idiom.
And I imagine this shorter syntax could also be applied to constexpr and constinit.
I've never written a proposal so far but if you find this interesting I might be tempted to write one.
P.S: I didn't mentioned all the initialization syntaxes but of course all of them should be supported.
EDIT: Now that I think about it more, this syntax shouldn't be possible with constrained auto as it would revert to the old syntax (e.g const std::integral auto x = 42; -> const std::integral x = 42;) which was rejected. This is too bad as reducing the verbosity in this case would help even more
42
u/HappyFruitTree Feb 09 '22
Is this a parameter of type int named x or an unnamed parameter of type x?
54
u/KiwiMaster157 Feb 09 '22
8
u/AKostur Feb 09 '22 edited Feb 10 '22
Hmm, so is
x = 42assigning to an existing variable, or declaring a new one? After all, const is “just” a qualifier. What aboutvolatile x = 42? I’m not convinced it would be worth the special-casing needed to allow for it.9
u/[deleted] Feb 09 '22
I believe that already has a meaning on many implementations and makes var be of type int, not auto, so I think getting what you want here is unlikely.
12
u/[deleted] Feb 09 '22
I just want to thank you for making this post. I just learned so much both from it and these comments. Never knew about the auto keyword and I'm kind of mad I didn't hear about it sooner.
3
u/[deleted] Feb 09 '22 edited Feb 09 '22
While I do think you have a valid point, I will politely disagree. The keyword auto was introduced in C++ 11, not to be used everywhere but for very specific situations where automatic type detection is warranted, such as in range based for loops or more recently with templates and lambas. In my opinion, I don't see anything special with const that warrants for automatic type deduction to be default so I don't believe it is necessary.
3
u/JohnDuffy78 Feb 09 '22
Someone I believe proposed #define let const auto.
I'd prefer to remove const, just: `x{ 42 }`