C ++ operator and operator

Is there logic and operator in C ++? for example, an operator that works the same as && except that it also evaluates subsequent arguments, even if some previous ones have already evaluated false? The operator and bitwise operator, which I understand.

+8
c ++
source share
4 answers

The operator is indeed a bitwise operator. I assume you have something like

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

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

 bool bF = f(); bool bG = g(); if ( bF && bG ) { /*do something*/ } 

It also provides better readability and does not confuse other programmers who are trying to save your code. Ultimately, it's worth it.

+21
source share

In C ++ there is no such "always execute" operator.

My first tendency is that instead of looking for a new operator, you should overestimate your methods to eliminate any side effects that need to be performed. Perhaps this way you can just use && and be happy.

However, if you really want to complete all the operations in sequence, and then see if they all succeed, Lucian Grigore’s answer will probably be the best. It clearly defines that these are sequential steps that must always be followed. There is another 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) ... 
+4
source share

There is no logical & , only bitwise & .

If you want to avoid short circuits of logical operators, you need to use a proxy that will not be optimized by the compiler to achieve it (for example, a variational meta-template).

+1
source share

If you overload the & & operator, it will not have a short circuit.

 struct Bool { bool val; Bool(bool f): val(f) {} operator bool() { return val; } }; bool operator&&(Bool a, Bool b) { return (bool)a && (bool)b; } 

ref: paragraph 19, section 13.9 in the C ++ FAQ lite

Although, as mentioned, this is a very bad idea and confuses people. You might want to do this very limitedly, but if you have a very special case.

0
source share

All Articles