Better way to pass bool variable as parameter?

Eddie picture Eddie · Sep 23, 2015 · Viewed 13.7k times · Source

I am wondering if there is a better way to write this for better readability. If you have a function like below,

void animal(bool hasFourLegs, bool hasHead, bool hasBody);

When you call the function, you will end up with something like

animal(true, false, true);

and this makes me go take a look at the definition every time I encounter function like this.

SO...

I do something like this!

const bool HAS_FOURLEGS = true;
const bool NO_HEAD = false;
const bool HAS_BODY = true;

animal(HAS_FOURLEGS, NO_HEAD, HAS_BODY);

But I do not like to declare const bool every time I call the function.

It seems like CPP does not support something like

animal(bool hasFourlegs = true, bool hasHead = false, bool hasBody = true);

Is there any better and shorter way?

Answer

James Adkison picture James Adkison · Sep 23, 2015

When I run into issues related to this I sometimes create an enum even when there are only 2 expected choices:

For example, instead of the following function declaration:

bool search(..., bool recursive);

I'd go with:

enum class SearchOpt
{
    Recursive,
    NonRecursive
};

bool search(..., SearchOpt opt);

Therefore, the calling syntax changes from:

bool found = search(..., true);

to:

bool found = search(..., SearchOpt::Recursive);

Note: this avoids you having to create your own constants every time you call the function.

Edit

As others have suggested, instead of having separate bools for each option and thereby a separate enum for each it would make sense to have a single enum configured as bit flags.