Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is (bool | bool) safe?

Tags:

c++

c

I'm writing some C++ code, and I'd like to call two functions (checkXDirty and checkYDirty), and return true if either returns true. I need to evaluate both even if one returns true, so my first thought was to use

return checkXDirty() | checkYDirty();

This looks a little weird (dirty, perhaps). Does this always produce the correct result in C++? What about C, with the _Bool type? (This code might end up being adapted for either language, and I don't want unpleasant surprises when I port the code).

like image 589
nneonneo Avatar asked Feb 21 '13 00:02

nneonneo


1 Answers

I need to evaluate both even if one returns true, so my first thought was to use...

Then stop trying to be tricky and making your code fit in as few lines as possible. Just call both functions and make it obvious that they need to be called:

const bool x_dirty = is_x_dirty();
const bool y_dirty = is_y_dirty();
return x_dirty || y_dirty;

Next, rename or break apart your functions as is_xxx_dirty really should not be producing side effects. Your code is harder to maintain as a result

like image 183
Ed S. Avatar answered Sep 22 '22 06:09

Ed S.