C++ Standard Booleans - Switch - c++

It is OK to use the standard 'true' and 'false' inside a switch statement, like so:
void handle_a_bool (bool value_to_be_handled)
{
switch (value_to_be_handled)
{
case true:
// Yay.
break;
case false:
// #$#%.
break;
};
};
I guess what I really want to know is whether the standard 'bool' type in C++ is a constant or something else.

Yes, it is legal, but why would you do that? Just use this:
if (value_to_be_handled)
{
// ...
}
else
{
// ...
}
The version based on switch just makes the code harder to read and doesn't bring any additional benefit.

You may use it, but as for me it's extremely hard to read.
Why to not use just
void handle_a_bool (bool value_to_be_handled) {
if(value_to_be_handled) {
}
else{
}
};
?

Related

Is it possible to switch/control/predicate a member function call using a ternary?

The style of this is certainly questionable, but I'm curious if there is a "clean" way in C++ to do a refactor like the following.
Suppose we start with the working code:
if (shapeA.intersects(shapeB)) {
// ... lots of code
} else {
// lots more
}
And I want to do a quick and dirty comparison with my new intersection routine, I'd like to inject a ternary into this if conditional:
if (shapeA.(enable_opt ? intersects_optimized : intersects)(shapeB)) { // expected unqualified-id
// hooray, we are undisturbed
} else {
// lots more
}
As opposed to the pretty awful looking
if (enable_opt) {
if (shapeA.intersects_optimized(shapeB)) {
// ... lots of code
} else {
// lots more
}
} else {
if (shapeA.intersects(shapeB)) {
// trail of tears
} else {
// despair and suffering
}
}
The pain/ugliness involved scales somewhat with the complexity of the conditional inside...
I've tried a few ideas and although it seems like member function pointers are possible to use, it appears impossible to specify a particular overload when obtaining the function pointer for a member variable if that function name is overloaded.
There's a possible 'halfway-house' solution using the ternary which, although still repeating some code, involves only one if ... else test:
if (enable_opt ? shapeA.intersects_optimized(shapeB) : shapeA.intersects(shapeB)) {
// hooray, we are undisturbed
} else {
// lots more
}
Not sure if you count this as 'ugly' or not, though.
You could possibly do it by selecting between pointers-to-member-function, but it wouldn't be very pretty.
Just wrap the call:
bool TestShapeIntersection(const Shape& a, const Shape& b)
{
if (enable_opt)
return a.intersects_optimized(b);
else
return a.intersects(b);
}
Then:
if (TestShapeIntersection(shapeA, shapeB)) {
// hooray, we are undisturbed
} else {
// lots more
}
You can write the ternary as
if ((shapeA.*(enable_opt ? &Shape::intersects_optimized : &Shape::intersects))(shapeB)) {
// hooray, we are undisturbed
} else {
// lots more
}
But it is not a lot prettier.
Note that
you cannot drop the &Shape:: part;
you need the additional pair of parentheses;
it is not exactly idiomatic.
The alternatives that move the call into a helper function are preferable.

Alternitives to C like labling and escaping nested loops for C++

In C and in javascript I enjoy the ability to write this kind of thing and have it just work.
while (a)
{
ctx: while(b)
{
while (c)
{
if(d) break ctx;
...
}
}
...
}
Perhaps I'm just confused about C++ versions but I get this kind of error in g++:
error: expected ‘;’ before ‘ctx’
break ctx;
error: ‘ctx’ was not declared in this scope
warning: label ‘ctx’ defined but not used [-Wunused-label]
ctx:
C++ appears to refuse letting me write this code.
C++ has added lambdas/closures that potentially would let me do this but I'm not quite sure how they would work in this case.
Using try throw catch is the closest construct I can think of that produces this behavior but the sloppiness of using an error system when none should be needed concerns me (Also they are slow I hear).
I'm tempted to just wrap it in extern C except I'm relying on c++ library's completely for the entire project so this also feels sloppy.
Is a try block or just rewriting my only options?
Neither C nor C++ have a labelled break statement (You're probably using a language extension, rather than standard C).
Instead, you can use goto to break out of a nested loop.
while (a)
{
while(b)
{
while (c)
{
if(d)
goto break_b;
}
}
break_b:
// ...
}
I was able to use goto to solve this... I though it was a banned construct in c++?
No. goto is not "banned" in C++.
This is a completely fine way to use goto. There doesn't exist an equivalent structured control statement.
lambdas/closures [...] potentially would let me do this but I'm not quite sure how they would work in this case.
If you are allergic to goto, then you can indeed use a lambda, but I don't see it providing any additional readability:
while (a)
{
[&](){
while(b)
{
while (c)
{
if(d)
return;
}
}
}();
// ...
}
Instead of a lambda, you can use a named function. But in that case you need to pass any variables (such as b, c and d) as arguments (assuming they're not globals).
Yet another way is an extra variable:
while (a)
{
bool break_b = false;
while(b)
{
while (c)
{
if(d) {
break_b = true;
break;
}
}
if (break_b)
break;
}
// ...
}
Of these three methods, I recommend goto, since it's the most readable. Except in the case the actual inner loop omitted from the example is very long, in which case a separate function might be better.
As has already been pointed out by others, goto would be a way to do exactly what you're asking for.
That being said, I would argue that, before asking the question of how to break out of a massively-complicated control flow structure, you should first ask yourself why there is a massively-complicated flow structure to begin with. What is going on in these loops? Should whatever is going on in each of these loops not better be moved into its own function? For example, instead of
while (a)
{
ctx: while (b)
{
while (c)
{
if (d) goto ctx;
…
}
}
…
}
why not
bool doC()
{
while (c)
{
if (d)
return false;
…
}
return true;
}
void doB()
{
while (b && doC());
}
and then
while (a)
{
doB();
…
}
Replacing the break with a goto here is not advisable. There can be issues wrt constructors and destructors not being called correctly. Whilst goto still exists in C++, it's really not something you want to use unless you really know what you're doing! A safer option would be to use a try-catch block. A better approach would be to re-factor your algorithm (currently it's O(N^3), which should really be ringing some alarm bells!)
while (a)
{
try
{
while(b)
{
while (c)
{
if(d) throw;
}
}
}
catch(...)
{
}
}

Is it possible to go to higher level scope condition's else in C++?

I have the exact same lines of code in the both do something section so I want to merge the two sections into one.
But I don't want to create a separate function for do something.
Is there a way to go to condition A's else when it reaches condition B's else?
if (conditionA)
{
//some code here
if (conditionB)
{
}
else
{
//do something
}
}
else
{
//do something
}
Jumping through code is definitely discouraged, if you really want to minimize the code then the only thing you can do is to rearrange the flow to better suit your needs, eg:
if (conditionA)
{
some code
if (conditionB)
do something else
}
if (!conditionA || !conditionB)
do something
If you (as indicated in the comments) don't want to create a function that you need to pass 6 arguments, then you could use a lambda like this:
const auto do_something = [&] { /* do stuff with captured reference variables */ };
if (conditionA) {
// some code here
if (conditionB) {
// stuff
} else {
do_something();
}
} else {
do_something();
}
if-else is really just syntactic sugar for gotos. You can use an explicit goto here:
if (conditionA)
{
//some code here
if (conditionB)
{
}
else goto do_something;
}
else
{
do_something: /*...*/;
}
This could/should be faster than adding another if check.
Alternatively, you can use an inlinable static function. There should be no performance difference if it does get inlined (and it won't piss off gotos-considered-harmful dogmatists).
(In my opinion, an occasional, clean, downward goto won't harm the readability of your code, but the dogmatism against gotos is strong (as evidenced by downvotes on this answer :D)).
Given that there is no code after //do something, You can use a pattern such as
if (conditionA)
{
//some code here
if (conditionB)
{
//do something else
return;
}
}
//do something
However a clearer pattern would be to encapsulate //do something into a separate function.
To answer what you are asking in the title: Yes, it is possible. There are at least three ways I can think of:
Using goto's (highly discouraged)
Putting "do something" code in a function (perhaps inline for performance) (may result to cleaner code)
Reformatting your if/else statements and merging your conditions as demonstrated in other answers. The rationale is to group the code segments that appear twice (by unifying logical expressions using operators). (I would prefer this way if the code is not that large or if it has high dependencies with other parts)
I would change conditions and rearrange the code a bit.
if (!conditionA || (conditionA && !conditionB))
do_something();
else if (conditionA) {
some_code_here();
if (conditionB)
// Your `if(conditionB)` section goes here.
}
Another possibility (one I think is often preferable) is to combine the conditions into a single variable, then use a case statement for the combinations:
unsigned cond = ConditionA | (ConditionB << 1);
enum { neither, A, B, both};
switch (cond) {
neither: // Both A and B were false;
A: // Only A was true;
B: // Only B was true;
both: // both A and B were true;
}
Then when you want the same code executed for two conditions, you just let normal switch fall-through happen.
You can wrap it up into cthulhu loop and use break:
for(;;) // executed only once
{
if (conditionA)
{
//some code here
if(conditionB)
{
// some more code here
break; // for(;;)
}
}
//do something
break; // for(;;)
}
I think this is more alegant then use for(;;) (VTT answer, which I upwoted)
do
{
if(conditionA )
{
//some code here
if(conditionB)
{
//some code
break;
}
}
// do something
} while(0);

Common If Structure

More and more I find myself writing a structure of If statements that looks like this:
if(something) {
if(somethingElse) {
// If both evaluate to true.
doSomething();
}
else {
// If the first if is true but the second is not.
doSomethingElse();
}
}
else {
// If the first evaluates the false.
doSomethingDifferent();
}
Now, to me, this looks horrific. Does anyone have a cleaner way of representing this logic?
The question as-is has three cases: something & somethingelse, something & !somethingelse, and !something. The alternative is to break it out into an if-else with three branches:
if(something & somethingElse) {
// If both evaluate to true.
doSomething();
}
elif(something) { // explicit test of somethingElse falsity not required
// If the first if is true but the second is not.
doSomethingElse();
}
else {
// If the first evaluates the false.
doSomethingDifferent();
}
For such a simple case, I usually prefer to flatten the structure as above. For more complex cases, it can end up being simpler to nest, or even better to reduce your tests to some kind of structure (a list or integer depending on your language) and switch on that value.

C or C++ Return Status

What are the best practices for writing C or C++ functions that return an int that represents a status code?
Specifically, I want to know about the client usage but other tips are welcome.
For example, can I write something like this:
int foo() {
return 0; // because everything was cool
}
And then use it like this?
if (foo()) {
// what to do if false, e.g. non-zero, e.g. not OK
} else {
// what to do if true, e.g. zero, e.g. OK
}
This should work because best practices typically dictate that a status code of 0 means everything was OK and also 0 means false in a boolean statement.
However, this wouldn't be good, right:
if (!foo()) {
// what to do if true
} else {
// what to do if false
}
We use this in C where I work:
int err = foo();
if (err) {
// armageddon
}
The assignment and if could be combined, but with more complicated function calls it gets more confusing and some people are confused by assignment in a conditional (and gcc hates it).
For C++, I would prefer exceptions if available, otherwise the above.
Edit:
I would recommend returning 0 on success and anything else on error. This is what unix command line utilities do.
If you really want to use status codes that way, use them with an enum or block of #define statements that describe the intention of the status code.
For example:
enum
{
kSuccess = 0,
kFailure = -1,
}
function foo()
{
return kSuccess;
}
if (kSuccess == foo())
{
// Handle successful call to foo
}
else
{
// Handle failed call to foo
}
This way, the intention is clear and there's no error-prone guesswork when someone wants to use or maintain your code in the future.
if (foo()) {
// what to do if false
} else {
// what to do if true
}
The problem with this approach is excess nesting. Suppose you have three functions you want to call:
if(foo1()) {
if(foo2()) {
if(foo3()) {
// the rest of your code
} else {
// handle error
}
} else {
// handle error
}
} else {
// handle error
}
To solve the excess nesting problem, invert the return value:
if(!foo1()) {
// handle error
return;
}
if(!foo2()) {
// handle error
return;
}
if(!foo3()) {
// handle error
return;
}
This solution suffers from another problem. It mixes the program logic with the error handling code. This complicates everything. Ideally, you want the program logic and error handling separated. This problem can be fixed with the goto
if(!foo1())
goto error1;
if(!foo2())
goto error2;
if(!foo3())
goto error3;
return;
error1:
// handle error
return;
error2:
// handle error
return;
error3:
// handle error
return;
Much cleaner.
Also, the goto can solve the problem of resource deallocation. See Using goto for error handling in C by Eli Bendersky for more details.
The return statuses should be defined in your interface and known to the caller. Some return 0 on failure (because it's easy to check with !), some return 0 on success (because they have enum of error codes, with OK being the first item).
There's no law or standard, each interface defines its own conventions. In C++ - use exceptions.
Best practice is to document your code so that yourself and others can quickly look up what the return codes will be when doing error checking.
Just jumping on board with another option that may be appropriate in your circumstances:
enum fooret { GOOD, BAD, UGLY, WORSE };
fooret foo(); // defined elsewhere
switch(foo())
{
case BAD:
case UGLY:
// maybe a recoverable failure(s)...
// take appropriate actions
break;
case WORSE:
// maybe non-recoverable
break;
case GOOD:
// successful, take appropriate actions
break;
}
int foo() {
try{
...
return 1
}
catch
{
return 0; // because everything was cool
}
}
I would start by wrapping everything in a try/catch block. Also instead of using and int it might make more scene to return a Boolean value. This is just a little more intuitive when testing in the if statement.