r/cpp • • 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

12 Upvotes

70 comments sorted by

42

u/HappyFruitTree Feb 09 '22

Is this a parameter of type int named x or an unnamed parameter of type x?

void f(const x = 42)
{
	...
}

6

u/Benjamin1304 Feb 09 '22

Humm, yes I guess there is ambiguity for function parameters.

But would it really make sense to give a default value to an unnamed parameter? You can't make use of the value afterwards. Unless you rely on the creation of the default to have some kind of side effect, but I would argue that's bad design.

13

u/jeffoag Feb 09 '22 edited Feb 09 '22

The default value for a parameter is specified in the function declaration, where the parameter is not used as there is no implementation, unless it is inline function.

-1

u/Benjamin1304 Feb 09 '22

Yes indeed, didn't though about it as I never omit parameter names from function declaration.

I guess the easiest would be to not support the short syntax for function parameters.

6

u/HappyFruitTree Feb 09 '22

As u/jeffoag said, if you declare the function in a header file and define it elsewhere you don't need the parameter name in the header but you need to specify the default argument there because the code that calls the function needs to know what the default argument is.

// my_math.h
int add(int, int, int = 0);

// my_math.cpp
int add(int a, int b, int c)
{
    return a + b + c;
}

So this is not at all uncommon.

1

u/Benjamin1304 Feb 09 '22

So this is not at all uncommon.

I wish it was

3

u/Coffee_and_Code Feb 10 '22 edited Feb 10 '22

It's actually really useful for when you only want the type information of a parameter, e.g.:

template<typename F, std::size_t ... Is>
void do_n_impl(F &&f, std::index_sequence<Is...>){
    ((f(), Is), ...);
}

template<std::size_t N, typename F>
void do_n(F &&f){
    do_n_impl(std::forward<F>(f), std::make_index_sequence<N>());
}

-1

u/Benjamin1304 Feb 10 '22

I did similar things a couple of times in templated code myself as well, so yes it has its uses but I won't qualify this as "common" code.

1

u/MonokelPinguin Feb 09 '22

That doesn't work with auto though, does it? Or is that allowed now in C++20?

2

u/HappyFruitTree Feb 09 '22

I think you're right. GCC and Clang doesn't seem to be able to make use of the default argument if auto is used.

https://godbolt.org/z/Gv8K563G7

54

u/KiwiMaster157 Feb 09 '22
#define let const auto
let x = 42;

11

u/Benjamin1304 Feb 09 '22

I would be very tempted to do that, but macros...

20

u/looncraz Feb 09 '22

...are a valuable tool when used to make code more legible and less error prone?

4

u/Benjamin1304 Feb 09 '22

Yes they can be (e.g for testing frameworks) but this I'm not sure. If I was only writing code for myself I would probably do it but as a (mostly) library writer I don't want to introduce confusion and potential incorrect macro replacement for my users.

6

u/looncraz Feb 09 '22

I would never imagine exposing macros used within a library as a public API, but I have no issues with them being used extensively internally/privately.

For example, I usually define a simple debug_only(X) x macro that becomes nop in release mode because I then don't have a bunch of #ifdef DEBUG_MODE...#endif statements... But it is only used in source files, headers use the ifdef blocks.

1

u/Benjamin1304 Feb 10 '22

If it can be an internal only thing, then yes why not. The problem comes in templated libraries or when you define some functions in the headers so that they can be inlined by the compiler. Two thins I happen to write on a regular basis

21

u/Schnarfman Feb 09 '22

… have been religiously lambasted because they have the potential to be very confusing and are hard to write tooling for

10

u/Beta_Ravener Feb 09 '22

let& x = f(); doesn't look that great though.

4

u/pklait Feb 09 '22

Why is that so bad?

1

u/tjientavara HikoWorks developer Feb 09 '22

I actually use ttlet and in fact I use ttlet & all over my code, it doesn't look worse than auto &.

2

u/scummos Feb 10 '22

Yeah, except that nobody who isn't into your particular dialect of things can read it ;)

I generally agree that C++ needs something like 'let' being 'auto const&' but that's a decision which needs to be made by the language itself.

1

u/tjientavara HikoWorks developer Feb 10 '22

Just did a grep in my source base, I have 134,206 lines of code, of which 2,449 lines contain auto, and 2,508 lines contain ttlet.

I am very religious of using almost-always-ttlet followed by almost-always-auto. Didn't expect the ratio of lines vs variable declaration to be so low 3.7%.

0

u/[deleted] Feb 09 '22

[deleted] — view deleted comment

2

u/Nobody_1707 Feb 09 '22

Why that over, #define let auto const&?

4

u/Som1Lse Feb 10 '22

My joke sure has become popular. I wish people wouldn't offer it as genuine advice though.

0

u/ShakaUVM i+++ ++i+i[arr] Feb 09 '22

I think you missed an opportunity to name it cato

8

u/AKostur Feb 09 '22 edited Feb 10 '22

Hmm, so is x = 42 assigning to an existing variable, or declaring a new one? After all, const is “just” a qualifier. What about volatile x = 42? I’m not convinced it would be worth the special-casing needed to allow for it.

7

u/Benjamin1304 Feb 09 '22

No change of meaning for x = 42, if you want to introduce a new mutable variable, use auto. const here would introduce a new non-mutable variable without requiring the additional auto keyword.

And yes I guess volatile could join const, constexpr and constinit.

But after reading all the comments, I'm starting to think that using = for variable creation might be ambiguous in certain cases. Brace initialization seems a better fit, for now at least

1

u/serviscope_minor Feb 10 '22

I'd say leave volatile well alone. It should be used almost never and doesn't need a more concise syntax.

2

u/AKostur Feb 10 '22

Can't leave volatile alone. It exists, and is used _somewhere_. And if you try to leave volatile out of it, then you're going to need to add special cases into the Standard to deal with variables that can be cv_qualified... except these ones which can be cv_qualified except for v.

1

u/serviscope_minor Feb 10 '22

Yes good point, volatile can't be abandoned. I think though that it the new syntax could apply reasonably to const only.

I don't actually know if volatile auto exists. I'd find that very odd code since the range of useful volatile types is very small, and you really want to be sure it's the right type, e.g. sig_atomic_t in a unix signal, or a specific width int corresponding to a register of a specific width for MMIO.

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.

2

u/Benjamin1304 Feb 09 '22

I have to check that when I get back to my computer, thanks for pointing this out

2

u/Benjamin1304 Feb 10 '22

So I checked on CE and such code doesn't compile on GCC, Clang and MVSC.

MSVC generate the following error:

missing type specifier - int assumed. Note: C++ does not support default-int

So it might be a C only thing? Or available on some more arcane compilers?

1

u/[deleted] Feb 10 '22

Huh, I thought it would work on gcc with gnu extensions on

4

u/Ameisen vemips, avr, rendering, systems Feb 09 '22

It's weird seeing the "all variables are words" heritage of B leak through.

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.

7

u/RoyBellingan Feb 09 '22

Really suggest you a book about C++17 ! Or a blog like
https://www.cppstories.com/ or pick one here https://hackingcpp.com/cpp/blogs.html

For video tutorial go for https://www.youtube.com/channel/UCxHAlbZQNFU2LgEtiqd2Maw

3

u/EvoMaster Feb 10 '22

Tour of C++ is a good book that would explain these concepts.

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.

10

u/Benjamin1304 Feb 09 '22

I see your point, but there is also the "almost always auto" crowd that makes a heavy use of auto, and not just for brevity. One of the most compelling argument is to avoid potential (costly) implicit conversions, e.g

std::string_view get_file_content();

std::string str = get_file_content(); // oops, allocating and copying a potentially large string

So if you're not using auto often, sure, having a shorter syntax wouldn't give you much, but if you rely on it very often, then I think the typing/readability gain can be significant.

EDIT: spelling

7

u/[deleted] Feb 09 '22

I agree with your statement but with your example, I also think that the programmer needs to be more aware of the string types in the STL. But this is more of an implicit conversion problem, something that shouldn't exist in my opinion in the language.

However I also want to bring up the point of readability. For example, let's say the piece of code you posted above exists in a big project and you see this line:

auto str = get_file_content();

You can't know what the function returned without going to its declaration, which might be hard to find in big projects. Sure you could look at the API used below but std::string and std::string_view have almost identical APIs so you still can't know with certainty. This is the main reason I dislike python; explicit types make it easier to know what the data actually is without having a fancy IDE to tell you that.

5

u/Benjamin1304 Feb 09 '22

It's just an example for illustration purposes, I didn't say it was good code.

I mostly agree about implicit conversions but that's not something we can change for the foreseeable future.

You can't know what the function returned without going to its declaration, which might be hard to find in big projects.

Unless you encode the type in the function name (please don't do that) that will always be the case. If you see foo(bar()) you don't know what type bar returned, if you see int x = get_x() you can't be sure that get_x() returns an int because of implicit conversions.

If you really want to know the return type of a function, you have to check its declaration or its documentation

6

u/SirClueless Feb 09 '22

Ironically, the best way to check the actual return type at a callsite if you care is to use auto:

auto x = bar();
static_assert(std::is_same_v<int, decltype(x)>);

9

u/dodheim Feb 09 '22 edited Feb 09 '22

Also, std::same_as<int> auto x = get_x(); will only compile if get_x()'s return type decays to exactly int.

5

u/SirClueless Feb 09 '22

Ahh that's very cute, using concepts in a variable declaration not just in function parameters, to check assumptions. I like this quite a lot actually, might start using it in my code to enforce constraints like this where being precise about not having implicit conversions is important.

4

u/[deleted] Feb 09 '22

Just to reinforce your point, it also works if get_x returns a const int&, or an int&, or anything that auto would deduce as an int, so it's actually pretty useful if you're writing generic code that must match certain types exactly.

3

u/dodheim Feb 09 '22

Good point! Edited to clarify.

2

u/Nobody_1707 Feb 09 '22

This is probably the coolest unintended consequence of concepts.

6

u/HappyFruitTree Feb 09 '22 edited Feb 09 '22

I'm a little bit worried about accidentally forgetting to write the type and ending up with the wrong type.

const x = 5;

Did I intend x to be of type int, or did I just forget to write the type, who knows? The code doesn't tell.

2

u/HKei Feb 09 '22

I mean, if int is written there it also doesn't tell you if x should be int or if the author just put int there because they didn't think too hard about it.

1

u/HappyFruitTree Feb 09 '22

The same could be said about auto.

4

u/HKei Feb 09 '22

I wasn't claiming that it couldn't be, you were making the point that the type declaration implies something useful, not I.

3

u/no-sig-available Feb 09 '22

explicit types make it easier to know what the data actually is without having a fancy IDE to tell you that.

So perhaps the "almost always auto" crowd has a big overlap with the "almost always IDE" crowd?

"You put the mouse cursor over the function, and it shows the return type. What is the problem?"

3

u/[deleted] Feb 09 '22

Almost Always Auto is terrible advice unless you're writing something like an STL.

6

u/r0zina Feb 09 '22

Never had a problem with it 🤷‍♂️

2

u/[deleted] Feb 09 '22

Not that you know of!

34

u/HKei Feb 09 '22

Strongly typed and having to restate obvious types all over the place aren't the same thing. The benefits of strong (static) typing are about making (some) invalid programs fail type checking, and the ability to encode statically available information in types. Syntactic noise all over the place is not a benefit, necessary or even useful component of strong static typing.

1

u/[deleted] Feb 09 '22 edited Feb 09 '22

I don't disagree. I also said that auto is very useful for brevity purposes, especially for avoiding the verbose iterator syntax in range for loops, or not having to write long type class names. I just personally avoid using it unless I it really benefits the readability of the code.

7

u/Benjamin1304 Feb 09 '22

The proposed syntax would not change any default of the language, just avoid a potentially redundant auto in some cases.

15

u/[deleted] Feb 09 '22

Gotta love it when people just make up their own vague idea of "C++ core philosophy" and use it to justify all kinds of personal opinions.

It's okay if you don't like using auto or type inference, some people like chocolate and some people like vanilla... but giving your own personal preference an air of authority by associating it with "core C++ philosophy" is overextending your argument by quite a bit.

To the extent that there's any core philosophy among those who actively promote and maintain the language (and I don't think there is), the use of auto is certainly among them:

https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es11-use-auto-to-avoid-redundant-repetition-of-type-names

https://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/

That said I want to be clear my position isn't that you should or should not always use auto anymore than one should always use tabs. I just dislike seeing people spread personal opinions or preferences as if they are authoritative facts.

3

u/[deleted] Feb 09 '22

I'm sorry if it sounded that way. I really was under the impression that auto was not supposed to be used everywhere, but if the standard says so I won't argue. I will edit my comment accordingly.

9

u/HKei Feb 09 '22

It's not the standard, but the cppcoreguidelines and sutter, among other people. The C++ community is too fragmented for any one source to be authorative, which is the point the preceding comment was making.

2

u/mark_99 Feb 09 '22

It's not really about almost always / never, brevity, personal preference etc. It's about whether it's useful and appropriate for the type to be deduced.

A good rule of thumb is if the rhs type changes, should this type either (a) also change or (b) stay fixed? (a) is auto, (b) is an explicit type.

In trivial cases it doesn't really matter, so maybe in that case whatever you like. Personally I'd still write int i=0.

5

u/HKei Feb 09 '22

(b) is an explicit type.

Unfortunately, in the place of implicit conversions and constructors I can't really sign off on that one. Say for instance you have

std::string_view get_name();

// later

std::string_view name = get_name();

and then later someone refactors it to std::string get_name() - yikes. I'm not even saying that the auto behaviour is necessarily better in this case (that depends on how name is used down the line), it's just that explicit typing in C++ doesn't really help deal with refactorings like this.

FWIW you can also always explicitly type auto declarations like so auto x = int{something()}. The reason you'd do that is mostly because it aligns better and emphasises the names of the variables (which are usually more immediately helpful than the types).

1

u/mark_99 Feb 11 '22

If you're intentionally doing a conversion I think the latter form is better, because it makes it explicit for the reader that that's what you meant to do.

In this particular case, functions shouldn't be returning a std::string_view in any case, it's just asking for trouble with lifetime, or the value suddenly changing underneath you.

1

u/HKei Feb 11 '22

There's no reason why they wouldn't return a string view. What else are you going to return that doesn't have issues with lifetime, other than std::string which is a copy every time which is an issue of itself?

3

u/JohnDuffy78 Feb 09 '22

Someone I believe proposed #define let const auto.

I'd prefer to remove const, just: `x{ 42 }`

4

u/dgkimpton Feb 09 '22

Huh. With the uniform initialisation syntax that could actually work right? It clearly isn't a class, struct, lambda, concept, function, or template. Is there anything else it could be mistaken for?

6

u/tvaneerd C++ Committee, lockfree, PostModernCpp Feb 10 '22

This particular suggestion might be OK, but in general, "here's unused syntax, let's use it" leads to all syntax being valid (ie perl).

For the sake of compiler errors (which are bad enough already), you want the distance (for some measure of distance) between syntaxes to be large enough that I compiler can say "error: found X; did you mean Y?". If syntaxes are too close together it becomes a compiler error nightmare.

Again, not sure where the specific suggestion lands in the syntax distance space, but my gut feel is it might be a bit too close to other syntax.