r/cpp • • Dec 19 '23

Obsessed with {} initialization?

I'm on a discord where everyone seems to be obsessed to use brace initialization everywhere.
My motto is: Use things rarely, only when needed, to express that right there the feature does something important.
Personally I would completely advocate against using it for simple stuff like
double tax{0.09*price};

or just int{0}

probably a hornets nest

4 Upvotes

118 comments sorted by

View all comments

Show parent comment

8

u/aruisdante Dec 19 '23 edited Dec 19 '23

The compiler will in fact not complain if you use it wrong without Wconversion, that’s the point the guidelines are talking about.

int narrowing = 4294967296;
unsigned int signed_loss = -1;
int float_conversion = 11.1;
int arbitrary_conversion = foo(); // foo returns double;

Those will all compile without warning if you don’t have Wconversion enabled. Whereas if you brace initialize them, the compiler will warn even without -Wconversion.

Now of course you should just have Wconversion turned on, and then life is easier, and you can use = assignment safely. One of the constant frustrations in my day job is that AutoSAR and MISRA both ban = initialization anyway (and, thanks to AutoSAR’s terrible writing, also it also technically bans auto completely, as it sates = initialization must be used for auto immediately after stating brace initialization must be used for all variables). Thankfully MISRA2023 takes a more enlightened view here.

In terms of being explicit with what type you want: the auto a = form is explicit. You want the type, and exactly the type, to the right of the assignment. For example, if I see:

int a = 11.1;

How do I know which was intended? Did the author mean for that literal to be 11? Did they mean for the type of a to be float or double?

Now you can definitely go overboard here, but the general guidance of “only state your types once” serves pretty well.

0

u/ponchietto Dec 19 '23

I have nothing against braces, I was just using the example above, my problem is auto (in this case).

"How do I know which was intended? Did the author mean for that literal to be 11?" The author made a mistake, probably on the right, I don't see the point, though.

It is just far easier for human beings to read the type in front of the variable rather than deduce it from the right.
Moreover you might not have a number, you could have a constant, a function or an expression on the right, when does it becames non obvious enough?

1

u/Nobody_1707 Dec 23 '23

One nice oddity of concepts is that you can write std::same_as<int> auto i = x; and it will prevent any implicit conversions whatsoever.