Search code examples
c++conventions

Is there a convention for setting variables based on arguments?


Say I have a function with a flag or something:

void foo (Param p1, Param p2, bool setVariable)
{
    //if setVariable is true, set some bool var to true, else false
}

Is there a strong preference of one over the other of the following?

if (setVariable)
    _someClassVariable = true;
else
    _someClassVariable = false;

or

_someClassVariable = setVariable;

Obviously the second is less typing, but the first strikes me as more readable. Which one would be preferred?


Solution

  • I would generally prefer the second. To me, the first would be a strong warning that whoever wrote the code was barely competent at best.

    That said, I'd also tend to recommend against passing a bool as a parameter as a rule. It's rarely immediately obvious what foo(true); vs. foo(false); really means. It's usually better to use an enumeration so you get foo(do_this); vs. foo(do_that);