Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to pass bool variable as parameter?

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?

like image 552
Eddie Avatar asked Sep 23 '15 15:09

Eddie


1 Answers

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.

like image 126
James Adkison Avatar answered Oct 01 '22 14:10

James Adkison