0

I have this simple program here:

#include <iostream>
#include <bitset>

using namespace std;

int main() {

unsigned char a = 0b11100111; 
if((a & (1<<2)) == true) // THIS IS THE LINE
    cout << "Entering if block!" << endl;
else
    cout << "Too bad, maybe next time.." << endl;
bitset<8> x(a & (1<<2));
cout << x << '\n';
}

Can you tell me why this if((a & (1<<2)) == true) outputs: Too bad, maybe next time.. 00000100

While this if((a & (1<<2)) outputs: Entering if block! 00000100

I'm compiling with g++ -std=c++14.

Barnercart
  • 1,523
  • 1
  • 11
  • 23

2 Answers2

4

0b100 is a number and shouldn't be compared against true.

Try changing your if statement to:

if (a & (1<<2))

or equivalently

if((a & (1<<2)) != 0)

since in an if statement, anything not zero is considered true.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
Larry B
  • 194
  • 14
  • 1
    Just one more reason to not use `== true` in conditions. – NathanOliver Dec 13 '19 at 17:13
  • It may be worth mentioning that this happens because `true == 1` in a numerical context. – Lukas-T Dec 13 '19 at 17:15
  • Thanks! So basically for what concerns binary numbers (in 8bit for instance), everything that isn't 0000 0000 is considered equal to 1? – Barnercart Dec 13 '19 at 17:26
  • @Barnercart anything that is *not* `0` (zero) is considered `true`. `0` is considered `false`. – Jesper Juhl Dec 13 '19 at 17:31
  • 2
    @Barnercart, In an `if` statement, anything not zero is considered true. In your case, it may be clearer to put `if((a & (1<<2)) != 0)` as your if statement. – Larry B Dec 13 '19 at 17:32
  • @LarryB: Hope you don't mind my edit (and have an upvote) - your last comment really nails it; worth promoting to the answer. – Bathsheba Dec 13 '19 at 17:35
  • I see now. `if((a & (1<<2)) != 0)` indeed works like a charm. Thanks to everyone! – Barnercart Dec 13 '19 at 17:41
2

This epitomises the pitfalls in using superfluous == true which some folk like to use in the purported interests of clarity: sometimes it breaks code.

When (a & (1<<2)) == true is evaluated, true (a bool type) is implicitly converted to an int type with value 1, and for that matter a is converted to an int type too.

But (a & (1<<2)) is not 1, so the else is ran.

Did you want the far more normal if (a & (1<<2))?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483