Nischal
Nischal

Reputation: 67

Strange behavior of Boolean type in c++

I have the following if statement in my code:

~(( APQState  == dot11->tempState[0] ) &&
  ( STAQState == dot11->tempState[1] ) &&
  ( tempk1    == dot11->tempState[2] ) &&
  ( tempk2    == dot11->tempState[3] ) &&
  ( tempk3    == dot11->tempState[4] ))

Let say the boolean variable,

B = ( APQState  == dot11->tempState[0] ) &&
    ( STAQState == dot11->tempState[1] ) &&
    ( tempk1    == dot11->tempState[2] ) &&
    ( tempk2    == dot11->tempState[3] ) &&
    ( tempk3    = =dot11->tempState[4] )

The if statement is being evaluated even when B is true ( => ~B is false).
I checked the value of B inside the loop when it executes. I get B=1;

Strangely when I try to cout the value of (~B ), it shows a value of 2. ( i.e when B = 1).

Why is this happening?

Upvotes: 1

Views: 140

Answers (3)

Foggzie
Foggzie

Reputation: 9821

The tilde (~) in C++ is a Bitwise NOT Operator. This is different than the Logical NOT Operator (!).

~B does not always equal !B

Upvotes: 1

user1252446
user1252446

Reputation:

Make sure you know what you want.

~ is bit operator to flip all the bits.

! is the logic operator for "NOT".

Upvotes: 5

Himz
Himz

Reputation: 523

Change ~B to !B. That should hopefully work

Upvotes: 1

Related Questions