C++ Logical & Operator – Usage Guide

c++

Is there a logical & operator in C++? e.g. an operator that works just as && except that it also evaluates later arguments even if some preceding ones have already evaluated to false? The operator & is the bitwise and operator I understand.

Best Answer

The operator & is indeed the bitwise operator. I'm assuming you have something like

if ( f() && g() ) { /*do something*/ }

and you want both f() and g() to execute, regardless of whether one of them was evaluated to false. I suggest you do something else instead:

bool bF = f();
bool bG = g();

if ( bF && bG ) { /*do something*/ }

This also provides better readability and doesn't confuse other programmers who try to maintain your code. In the long run, it's worth it.

Related Question