Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I return bool or const bool?

Which is better:

bool MyClass::someQuery() const;  const bool MyClass::someQuery() const; 

I've been using 'const bool' since I'm sure I remember hearing it's "what the ints do" (for e.g. comparison operators) but I can't find evidence of that anywhere, mostly due to it being difficult to Google and Intellisense not helping out any ;) Can anyone confirm that?

To me returning const values (this isn't just about bools) makes more sense; it'll prevent temporaries being modified, which is almost always going to be a programmer mistake. I just want something to back that up so I can extol returning const values to my colleagues :)

like image 657
Ben Hymers Avatar asked Sep 18 '09 10:09

Ben Hymers


People also ask

What is const bool?

C++ Basic Type Keywords boolAn integer type whose value can be either true or false . bool is_even(int x) { return x%2 == 0; } const bool b = is_even(47); // false.

What does bool& do in C++?

A boolean data type is declared with the bool keyword and can only take the values true or false . When the value is returned, true = 1 and false = 0 .

Should I use bool C++?

It is something C programmer use, but C++ programmers should avoid, since C++ has bool . bool is a language integral type whose supported values are just true and false . When converted to int true becomes 1 and false becomes 0.

Why is const correctness important?

The benefit of const correctness is that it prevents you from inadvertently modifying something you didn't expect would be modified.


1 Answers

This is the case when const adds no value but inflates the code and makes the reader think more. What's the point of this const? The caller can copy the value into some non-const variable and do whatever he wants with it anyway.

like image 61
sharptooth Avatar answered Sep 25 '22 04:09

sharptooth