16 August 2009

Short-Circuit Evaluation

In C++ the functions a, b and c given below are functionally identical. There may be good reasons to write a or b, but assuming there aren't, I prefer c.

Function a feels strangely asymmetric. Function b has more symmetry, but is rather verbose. Function c is short and to the point.


bool foo(int &);
bool bar(int &);

bool a(int & n)
{
if (foo(n))
return true;
return bar(n);
}

bool b(int & n)
{
if (foo(n))
return true;
if (bar(n))
return true;
return false;
}

bool c(int & n)
{
return foo(n) || bar(n);
}

No comments:

Post a Comment