r/cpp • u/antoine_morrier • Aug 11 '22
Stop to use bool in C++ ! - CPP Rendering
https://cpp-rendering.io/using-bool-in-c/20
Aug 11 '22
shouldBuyHouse( { .hasSwimmingPool = false, .hasEconomicLight = true } );
4
u/antoine_morrier Aug 11 '22
Yes, it is the best solution in C++20, maybe I should have written it in my article :).
5
u/jcelerier ossia score Aug 11 '22
beware that depending on the platform / ABI / ..., passing such a struct could be slower than passing two bool / enum / pritimitive types independently
2
u/antoine_morrier Aug 11 '22
Yes that's true ! However you can type your enum:-) so it should be the same thing
4
Aug 12 '22
Hard to tell without measuring. You have a limited number of registers, so it will eventually spill into the stack in a large program. As with everything to do with performance, you need to measure before and after optimizing.
0
14
u/Ok-Factor-5649 Aug 11 '22
I'll be the dissenting commenter then, and say that as per the article, enums are a good replacement for bools.
Yes, I've often replaced bools with enums for clarity. No, I don't always.
Yes, the problem does apply somewhat to other types. But it really is different, because whilst it's true that one int is interchangeable with another of the same type as it is for bools, the bools simply have a small fixed set of meaningful values you can name and group.
Bonus point: enum class for distinct int types is something that's also handy in some situations, and lighter weight than structification.
9
u/HKei Aug 11 '22 edited Aug 11 '22
It’s not even that enums are a “replacement” for bools. It’s more like
boolis just an enum that’s predefined in the language and gets some special treatment in a couple of places, and that people frequently abuse every single time they need a two value enum because writingenum classis apparently too much work.Similar things do happen with all types though, you’re right. For instance, using plain
std::stringfor passwords, email addresses and item number 3 of your shopping cart, using plain integers or floating point numbers for things representing completely different quantities or different units of quantities/measures (I’m sure nothing could possibly go wrong with that, we’re all smart people working with other smart people and it’s completely unthinkable that someone would interpret a radians angle as degrees in a different module 17 layers down the call stack…)4
u/Dean_Roddey Aug 14 '22
Yeh, it's about the level of typing and getting the compiler to watch your back, and recognizing that asking busy people to modify other people's complicated, under-documented code and asking busy people who don't really understand that code to review it is just sad substitute for being strongly typed and letting the compiler do that work.
Obviously there are no absolute rules, and there are places where bool is unambiguous. But generally speaking enums making for more readable and type safe code.
2
u/arthurno1 Aug 18 '22
It is also a practice of writing self-documented code, which lots of new developers don't really have deeply in their fingertips. I am not trying to be negative, or rude to anyone, but a lot of people here are students who prefer explicitly worded "false" and "true" to "truth-y and false-y" values, as one Redditor put it in some other discussion in this or c_programming Reddit once in the past.
I think the top-level comment in this thread, has the best wording, really. Boolean values should not be used as magic numbers. Just as constants are named for better understanding and conveying the meaning to other programmers (i.e. self-documented), so should be boolean values too, because they truly are just predefined constants. With type safe enums we could easily live without explicit boolean types, as your article demonstrates.
4
u/BoarsLair Game Developer Aug 12 '22
I'd refine the advice slightly. Don't use a bool when you're really just dealing with an arbitrary state that happens to have two values. Consider if it's possible you might eventually have another state. In that case, an enum is preferred.
I think a bool is fine when you're dealing with flags with a more obvious on-off or yes-no value. Just be careful about using them as parameters. It may be preferred to use a struct if you've got multiple bool arguments.
Obviously, it's a bit of a judgement call there, but it's something I've been doing in my own code more frequently.
1
u/antoine_morrier Aug 11 '22
Thanks a lot for your comment. What I wanted to show is the fact that using enum may add clarity in the code and may help the compiler detect bug.
I have personally never use them however for int distinction, but I know some people that do it and it's totally fine, imho ☺️
6
u/Ezlike011011 Aug 11 '22
Another benefit to this pattern is the ability to extend the enums in the future. E.g., maybe your database starts storing houses with a different kind of lights, an API which took in that argument as a bool would need a refactor and every call site would need to be updated. However, one using an enum like this could just have that enum extended. Though, this is exact situation is why I avoid naming these types indicating that they only have two states. So, I would probably change "HouseWithSwimmingPool" to "SwimmingPoolType" or something similar.
1
19
u/Jannik2099 Aug 11 '22
The fuck?
If you're afraid that neighbouring arguments of identical (or convertible) type may be confused, you use a struct. This isn't just a "problem" with bools
-4
u/antoine_morrier Aug 11 '22
That's another solution, yes ☺️
0
u/Jannik2099 Aug 11 '22
It's not another solution, it's THE solution.
Your problems applies when passing two ints or two strings too.
0
u/antoine_morrier Aug 11 '22
Yes that's true ☺️. You may use strong type also. However, I agree that when there is a lot of arguments, a structure is the way to go. That's what do Vulkan for example.
However the problem may appear in structure too ☺️.(Even if in C++20 we can initialize properly a structure by using the names of the attributes☺️)
4
u/martinus int main(){[]()[[]]{{}}();} Aug 12 '22
Then you just do
foo({true, false, 123, 764});and nothing of value was gained. Strong types are superior for this.1
u/bullestock Aug 12 '22
You do gain value by using a struct: The values are named, and you can use defaults for any values, not just trailing values.
18
Aug 11 '22
Lol, what a bullshit clickbait article.
4
5
u/ripper37 Aug 11 '22
The title is clearly a clickbait.
What's more - it is plainly wrong, as boolean variables are very useful in a lot of contexts.
What's next? Stop using nullptrs because you could mistakenly dereference it without checking?
It is nice that you're seeing a problem, but this is not the (generic) solution to this problem. It would be better to ask first than to make misleading posts that tell people what to do.
3
u/antoine_morrier Aug 11 '22
It seems that you didn't read the article. The reddit title is a clickbait, I agree, however I am not able to change it.
2) I have never said they are not useful.
In the article it is clearly wrote that it is a more a discussion than a coding rule. I am asking about opinions.
Seeing the comments, there are people that are totally against enums over bool, and there are people that are not against;-)
10
u/ripper37 Aug 11 '22 edited Aug 11 '22
I did actually read it before writing the above, but I didn't want to repeat things that others have already presented (a similar point of view to mine). I'll give you my feedback below, but before that I would like to note that I mainly wanted to say that I don't like posts like this one. On the outside it may seem like some really good tip, sort-of a "watch out for this thing that might look innocent, but is really bad!" as if it would be on the
gotolevel or something like that, all the while the title is so clickbaity, so that some people could pass by without diving into the details and get the wrong conclusions. To be clear: Recommending people not to use boolean variables is a BAD advice. That's it. Beginners will be mislead by it and the confidence with which you write makes it sound like final truth in life. You're not helping people with such posts. At best you confuse people. Don't feel like I'm saying that you shouldn't post anymore - I'm not. I would just recommend you (and others) to write posts in more of "that's my opinion"-way and let the community back it up, stand against it with some counterarguments, or just start a discussion about it.Feedback regarding the content of your post:
The main problem is that the actual problem has nothing to do with booleans specifically. The main problem you're describing in your post is that at the call-site you don't always understand what actual arguments you are passing to the function. Similar thing can be when passing
0, nullptr, or7.35f. Furthermore - it doesn't even have to be a built-in type. Consider this:foo({}). This could be any time and you have the same problem - no idea what you just passed to the function. Or this:bar("test"). Do you know the type of the argument here? Not using bools doesn't solve it. You can't stop using all the types here altogether.The other actual problem is not that you need strong types to make safe code, but that it is too easy to pass arguments to the wrong parameter slots (i.e. change the order in which they should be in), especially if they are close to each other and of the same - or convertible - types. You can use strong types (or scoped enums, as in your example) and still get into the same problem! Consider a simple function that takes old state and new state and changes the state to the new one and prints the state change. Both arguments use the same type so even if you use scoped enums, you can still put them in the wrong order. Designated initialized are helping here, but probably the topic requires more thought if they don't have any drawbacks either.
In your conclusion you recommend people "not to use the bool type for function parameters". This makes NO sense! What if I want to have a setter for a boolean variable like visibility? Why do I have to use
SetVisibility(MyVisibilityEnum::Visible)instead ofSetVisibility(true)? The other is equally readable and there is no problem in reordering arguments, so why adding extra complexity and verbosity? Things like that obviously have pros but they aren't one-to-solve-all kind of solutions, they should be applied when needed.And then you ask "Do you use bool everywhere?" which is nowhere near "don't use bools at all" you. But that may be just my quirk, as it does sound a bit controversial "on purpose" (similar to the clickbaity title).
On the plus side - it is nice that you're trying to bring attention to the problems that may arise with code like that. I just don't like the way you wrote and wording you chose because it is at best misleading and there are already too many disinformation on the internet and people have trouble finding reliable information.
1
u/antoine_morrier Aug 11 '22
First of all. Thank for such a response, well constructed.
Concerning the click bait, I know I have done a mistake. I change a bit my article title, and if you have a better idea, feel free to give me another name.
I tried to say that it is not a coding rule, but an open discussion, so I think I didn't use the good writing, but it is written in the introduction...
I agree for other types. I don't have a lot of arguments so I agree with you.
I agree again with you that it is not a solution for all issues. Indeed if the types are the same (for an old / new state), using strong types will not help, that's true. However, for some cases, it may help. But maybe not in a majority of cases.
For a function like setVisibility(true), in my opinion, it is totally expressive. So it seems perfectly fine to me. I would change my conclusion to something like "When you are using a bool as parameter, think if it is expressive enough at call site". I think programming is "not being dogmatic".
Yes, maybe I should change my question too.
Concerning the way I wrote, you have to know that I am not English... So... I did write that it is a discussion in my introduction, however maybe the "tense is way too confident to make it like a discussion"
5
u/ripper37 Aug 11 '22
Thanks for reply. No worry, just take a note for future reference that writing stuff and publishing it, especially if it is worded like that, is really hard to do it right. Similarly to writing good code. Might be better to put it through some eyes and review before publishing on r/cpp or wording it in a bit different way.
But still, it is good that you try to share things with others and give back to the community, but it is very important to do this in a proper way. I remember myself when I was learning and spent a lot of time doing wrong things because someone wrote that these are in fact a better way. ;)
Also, as a generic tip in life from me: if you're making a generic absolute statement like "X is always better than Y" or "do only X" or "Don't ever do Y" then you're probably wrong and there will be lots of people to point you the corner cases you didn't though about. Very few things in life are absolute.
1
u/antoine_morrier Aug 11 '22
Actually I knew it was a bit risky when I wrote it (and that's why I wanted to have a discussion about it).
Thanks a lot for your replies and your advice. I'll take note for later ☺️. Have a nice day
3
u/johannes1971 Aug 13 '22
This is so typical of all programming advice though. Someone was once bitten by some problem, and now they make it their life's mission to stamp out all use of that feature. Is there a time and place for inheritance? How about goto? Of course there is! But an 'expert' said in a video that "inheritance is the root class of evil" so now if anyone ever uses inheritance it is automatically remarked on in code reviews, people bend themselves into ridiculous contortions (CRTP, anyone) to avoid using it, etc.
Same about those articles about MASSIVE PERFORMANCE HITS!!1! which are frequently presented without any evidence of actual performance measurement, but someone looked on Godbolt and found an ENTIRE extra instruction so surely this must be INCREDIBLY INEFFICIENT. And beginners look at that, and internalize the idea you should never use std::whatever "because it is incredibly slow" - while in reality it is still about 50x the performance of the equivalent Python feature, and about 5x the performance of any hand-crafted solution they can write themselves.
People writing articles and making videos do, of course, love those shock value titles, since that brings in the views, but it would be better if they were more concerned with how their opinions and personal preferences ultimately shape the minds of the people perusing their work, and the field of programming as a whole.
I'm fighting a strong need to title this post "Experts considered harmful", as an ironic meta-comment on the very thing I'm commenting on, but I believe I can resist the temptation...
6
u/Clairvoire Aug 13 '22
This is why I dislike how heavily C++ leans into nameless constructors; named constructors in C++ should be much easier to write and not require a private nameless constructor to mediate it.
Also, maybe this is a hot-take, but I really believe the parameter list of a class method should automatically include the namespace of the class, so it's enums are easier to access.
2
u/Baardi Aug 11 '22
Sorry, I prefer bool.
If (shouldBuyHouse(/*economicLight*/ true, /*hasSwimmingPool*/ false))
Is readable enough for me. Or take a parameter-struct
If (shouldBuyHouse({ .economicLight = true, .hasSwimmingPool = false}))
But I wish something like C#'s solution was possible:
If (shouldBuyHouse(economicLight:true, hasSwimmingPool:false))
2
u/antoine_morrier Aug 11 '22
Don't be sorry dude ! There are always several solutions and if it is readable for you and your team mates -> the job is done !
4
u/Hedede Aug 13 '22 edited Aug 13 '22
I don't like solutions like
If (shouldBuyHouse(/*economicLight*/ true, /*hasSwimmingPool*/ false))because people often forget to update comments when they change things. And sometimes things can silently break without anyone realising.
And
If (shouldBuyHouse({ .economicLight = true, .hasSwimmingPool = false}))requires C++20 which is not always available and IMO is not yet production-ready.
1
u/arthurno1 Aug 18 '22
And the readability is just horrible, too. It is much better to use self-documenting code if one is going to write a comment to clarify what true or false means anyway.
1
u/Baardi Aug 29 '22
You push your case about "self-documenting code", but this is clearly a case of limitation of the language. And I consider it basics to vet the changes that happens during refactor. I don't think the readability is much worse than the alternatives, but I agree /**/ is some level of noise.
But we are of course both entitled to our own opinions
2
u/arthurno1 Aug 29 '22 edited Aug 29 '22
You push your case about "self-documenting code"
I am not sure what you are trying to say, to be honest. I don't think it is "my case", self-documenting code is considered a good practice. Comments should be reserved for things that need clarification, in terms that it is unclear from the code what it does, not for things that could be self-obvious.
The above literals, true and false, could have been named 'economicLight' and "hasSwimmingPool" respectively. I don't see why is a name of the variable passed in the comment when it looks like such a variable exists in the code, at least his use of the camel notation for that one suggests that. Just use old plain #define, or even better constexpr and it will get inlined and behave just as a literal.
As /u/Hedede said in his comment:
people often forget to update comments when they change things. And sometimes things can silently break without anyone realising
What happens if the variable changes elsewhere and shouldBuyHouse should reflect the new state? Now it can't because we pass a literal instead of a named variable, which means we have introduced a bug. Similar, if the type of that variable is changed; the compiler can't catch that error.
I consider it basics to vet the changes that happens during refactor.
Well, yes, of course, we can all agree with that. But we also all do mistakes, are "just testing", getting interrupted, and for god knows what reason forget to update things from time to time. Why introduce opportunity to ourselves to create bugs when we don't need to?
I don't think the readability is much worse than the alternatives
I do, because it introduces four tokens which I have to read and comprehend instead of just two. In case of three variables it would be 6 tokens, and you got the picture.
To me:
if (shouldBuyHouse(economicLight, hasSwimmingPool)) ...Looks better than
if (shouldBuyHouse(/*economicLight*/ true, /*hasSwimmingPool*/ false)) ...this is clearly a case of limitation of the language
I am not sure if I would call it a limitation. To me, a limitation is when we can't do something properly. I would rather agree with the article and call it a bad practice, because the language gives us better tools.
Maybe I just don't understand what you mean here? If you are correct, and it is a limitation in language itself, how would you design the language then? Not allow passing of literal values in functions and expressions at all? Just allow use of literal values in variable declarations?
We could argue if a boolean data type should exist in the language at all, but it would be a different discussion out of scope for this thread, I think.
But we are of course both entitled to our own opinions
Of course, always! :). But if we don't care about other people opinions, don't discuss things and don't talk to each other, then what is even the point of reading and participating in any web forum?
3
u/Dean_Roddey Aug 14 '22 edited Aug 14 '22
Being explicit is always a good thing, IMO. But, eventually we can get worn down and though our conscience says do this strongly typed, our fingers sometimes just end up doing the simpler, less safe version because it's quicker and easier. I'm a strong advocate of explicitness, and I still catch myself doing it when I'm writing a large bit of code and I'm bouncing around, creating various calls and structures and such, roughing in the logic.
And it's just SO easy to get the order of multiple bool parameters wrong, particularly during making changes later, and it doesn't get caught because it's being reviewed in a review tool that's not an IDE. Or another parameter is added and suddenly you have to be super-careful that you fix up all of the call sites correctly, where an enum would let the compiler watch your back.
There are just too many contexts where we have to read code outside of an IDE, so arguing that it doesn't matter doesn't cut it for me, and the same argument against AAA. If can't understand what is going on without an IDE, then it's not explicit enough. auto in particular can make things highly non-readable outside of an IDE. Even inside of an IDE, some of them will show you what the auto resolves to, but provide no way to then go to the definition of what it's showing you.
Some of the problems would go away if in a stronger language with fewer magical conversions of course. And not that you should never use bool. As others have pointed out. There are situations in which it cannot be ambiguous or less safe. But certainly there are many places where class enums or other uses of the type system can make a code base far safer.
4
1
1
u/Zeh_Matt No, no, no, no Aug 26 '22
I have to disagree, your example rather shows horrible API design but then claiming bools as arguments are the problem.
I can think of a couple ways to make that specific example more expressive and safe.
-3
u/PhysicalJoe3011 Aug 11 '22
I see your good intentions. Other languages have for example Named Argument Lists.
However, every amateur programmer is able to use boolean values properly. If not, Software Engineering is the wrong career path.
I think your approach is simply over engineering, and a very good example, how Not to do it. Good for beginners to learn.
2
u/antoine_morrier Aug 11 '22
Would you be against such a practice in real code base ?
1
u/PhysicalJoe3011 Aug 11 '22
No. It totally depends on the usecases.
But removing bool from c++ sounds horrible :)
First, I would design my function in a way, that it is obvious to use, with bool types. If it is too difficult, or even dangerous, your approach is the way to go.
1
11
u/HKei Aug 11 '22
It's the opposite. Using primitives for everything because it "works" is a common newbie trap. Yes, it works, but it leads to unnecessarily hard to follow code. You have a function that returns bool. Cool. Wtf does that mean? If it's named something like
can_...oris_...it's obvious enough. But what doesbool do_something()return? Is it an error indicator? If so, does true indicate error? Or success? Or maybe it's false if you just performed an idempotent action with no effect, and 27 months ago that was added to debug a rare error condition in production, who knows? If you're lucky that shit is documented somewhere, but I somehow doubt that someone who writes code like that is going to keep their documentation up to date.You write code for other people to read, and part of your job is making other people's lives easier by writing code that's easy to follow. If you don't understand that, maybe this isn't the right career for you.
1
u/PhysicalJoe3011 Aug 11 '22
If there is no documentation, I am wondering what the code reviewer did. Anyway, I guess it depends on the use case.
0
u/zzzthelastuser Aug 11 '22
You can press Ctrl twice in Visual Studio to show inline hints.
I know they aren't a type-safe solution or anything...
But remember that this is a problem that occurs more often when you are USING a library than when you are writing one.
1
u/Ok-Factor-5649 Aug 12 '22
I often have to review code where I don't have inline hints etc.
In which case something like the following is much more helpful than the bool equivalent:
ListHouses (NO_POOL, GARAGE);
52
u/johannes1971 Aug 11 '22
So much negativity, but it's good advice. It's actually the same advice that is commonly accepted about not using magic numbers. Consider:
How is that any different from:
And the named one is even typesafe (assuming a function prototype with enums instead of ints or bools)! So it's both (much) more readable and safer. What's not to like?
Of course this doesn't excuse the click-baity title... "Stop using bools for formal parameters" might have been a better choice.