rsethc
rsethc

Reputation: 2664

C++ Standard Booleans - Switch

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.

Upvotes: 1

Views: 191

Answers (2)

RiaD
RiaD

Reputation: 47619

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{
    }
};

?

Upvotes: 2

Andy Prowl
Andy Prowl

Reputation: 126432

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.

Upvotes: 4

Related Questions