Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ logical & operator

Tags:

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.

like image 208
Cookie Avatar asked Aug 01 '11 13:08

Cookie


2 Answers

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.

like image 52
Luchian Grigore Avatar answered Oct 12 '22 11:10

Luchian Grigore


There is no such "always execute" operator in C++.

My first inclination is that instead of looking for a new operator, you should re-evaluate what your methods do to eliminate any side effects that mandate they be executed. It may be possible in this way to simply be able to use && and be happy.

However if you actually want to do all the operations in sequence and then see if they all succeeded, probably Luchian Grigore's answer would be the best. It clearly delineates that it's sequential steps that always need to execute. There is one more option which may or may not be less clear:

// Each method needs to execute in sequence but we use "success" to track overall success. The order of operands to `operator&&` shouldn't be changed.
bool success = f1();
success = f2() && success;
success = f3() && success;

if(success) ...
like image 40
Mark B Avatar answered Oct 12 '22 12:10

Mark B