Reputation:
I have a question about "|=" in c++, how this operator works, for example:
bool result;
result |= callFunctionOne(sig);
result |= callFunctionTwo(sig);
result |= callFunctionThree(sig);
result |= callFunctionFour(sig);
and the function called above, will reutrn "true" if the paramater sig is processed in the function, otherwish, return "false";
the sig can be processed only in one function each time, how the "|=
" works?
Upvotes: 2
Views: 455
Reputation: 2275
The | operator is bitwise OR (if you know the boolean logic, on a bool variable it acts as a boolean OR). If one or many calls return true, result will be true. If all calls are returning false, the result is false.
Each time, it's the equivalent of result = result | callFunctionXXX(sig);
Remark: in your sample code, the variable result is not initialized. It should be "bool result = false;"
Upvotes: -1
Reputation:
|
is bitwise OR.
|=
says take what is returned in one of your function and bitwise OR
it with the result
, then store it into result
. It is the equivalent of doing something like:
result = result | callFunctionOne(sig);
Taking your code example:
bool result;
result |= callFunctionOne(sig);
result |= callFunctionTwo(sig);
result |= callFunctionThree(sig);
result |= callFunctionFour(sig);
and your logic of
will reutrn "true" if the paramater sig is processed in the function, otherwish, return "false";
So that means that if you don't define result, it will be by default FALSE.
result = false;
callFunctionOne
returns TRUE
result = result | callFunctionOne;
result
equals TRUE.
result = false;
callFunctionOne
returns FALSE
result = result | callFunctionOne
result equals FALSE.
While it may seem that this is a boolean OR
, it still is using the bitwise OR
which is essentially OR'ing
the number 1
or 0
.
So given that 1
is equal to TRUE and 0
is equal to FALSE, remember your truth tables:
p q p ∨ q
T T T
T F T
F T T
F F F
Now, since you call each function after another, that means the result of a previous function will ultimately determine the final result from callFunctionFour
. In that, three-quarters of the time, it will be TRUE and one-quarter of the time, it will be FALSE.
Upvotes: 7
Reputation:
To put it simple, it will assign true
to result
if any of those functions return true
, and false
otherwise. But there is one problem - result
must be initialized
, otherwise this bit operation will be performed on random initial value and could return true
even if all of the functions returns false
.
The operator itself is called "bitwise inclusive or".
Upvotes: 1