Reputation: 3761
We all know && (double and) for and condition. for single and What happen internally how condition gets executed.
if(true & bSuccess)
{
}
Upvotes: 7
Views: 18119
Reputation: 26940
In your case since bSuccess is bool then
if(true & bSuccess)
is exactly the same as if(true && bSuccess)
However had you used this :
short i = 3;
short k = 1;
if(i & k)
the result will be true :
0000 0000 0000 0011
&
0000 0000 0000 0001
-------------------
0000 0000 0000 0001 true
& operates on individual bits and here bit 1 is the same in both case so you have true as a result.
Hope that helped.
Upvotes: 8
Reputation: 133092
true & bSuccess
in this expression both operands are promoted to int
and then &
is evaluated. If bSuccess is true you will get 1 & 1
which is 1
(or true
). If bSuccess is false you'll get 1 & 0
which is 0
(or false
)
So, in case of boolean values &&
and &
will always yield the same result, but they are not totally equivalent in that &
will always evaluate both its arguments and &&
will not evaluate its second argument if the first one is false.
Example:
bool f() { std::cout << "f"; return false; }
bool g() { std::cout << "g"; return true; }
int main()
{
f() && g(); //prints f. Yields false
f() & g(); //prints fg or gf (unspecified). Yields 0 (false)
}
Upvotes: 17