Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If condition with single and (&)

Tags:

c++

We all know && (double and) for and condition. for single and What happen internally how condition gets executed.

 if(true & bSuccess)
{
}
like image 631
Sandip Avatar asked Nov 17 '11 12:11

Sandip


2 Answers

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)
}
like image 76
Armen Tsirunyan Avatar answered Oct 03 '22 01:10

Armen Tsirunyan


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.

like image 27
FailedDev Avatar answered Oct 03 '22 00:10

FailedDev