CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Guest

    Logical operators

    Hi
    The following demonstrates that bitwise & and | work similar to logical AND(&&) and logical OR(||).

    bitwise &
    (true & true):true
    (true & false):false
    (false & true):false
    (false & false):false

    bitwise |
    (true | true):true
    (true | false):true
    (false | true):true
    (false | false):false

    Then, why do we have logical AND and OR?


  2. #2
    Join Date
    Mar 2000
    Location
    Dublin, Ireland
    Posts
    124

    Re: Logical operators

    WhoeverYouAre,

    Bitwise operators are used to manipulate bits within a given value.
    For example:char x = 10; // x now holds the value 0000 0000 0000 1010
    if ( x & 1 != 0 )
    ...


    The if statement gets the value of x and does a bitwise & operation on it...
    0000 0000 0000 1010 - the value of x
    & 0000 0000 0000 0001 - the value 1
    ---------------------
    0000 0000 0000 0000


    As you can see, the resulting value is 0, so the if statement is FALSE.

    If we bitwise OR the two values:if ( x | 1 != 0 )
    ...


    ...the following occurs: 0000 0000 0000 1010 - the value of x
    | 0000 0000 0000 0001 - the value 1
    ---------------------
    0000 0000 0000 1011

    The resulting value is 11, a non-zero number, therefore TRUE.

    Logical operators, on the other hand, do not deal with bits at all.
    They deal with the entire expression.
    For example:int x = 10;
    int y = 23;
    if ( x == 10 && y == 21 )
    ...

    This if statement looks at each side of the && operator separately.
    Is x equal to 10? Yes.
    Is y equal to 21? No.
    A yes AND a no equals NO!
    The entire expression is FALSE.

    If we do a logical OR operation on it instead...if ( x == 10 || y == 21 )
    ...

    ...we get
    Is x equal to 10? Yes.
    Is y equal to 21? No.
    A yes OR a no equals YES!
    The if statement is therefore TRUE.

    If you really want to understand this fully, the best way
    is to keep practicing on paper. Otherwise, to answer your
    question, the bitwise operators are to manipulate a value while
    the logical operators manipulate an entire expression.

    Hope this hasn't confused you more.

    Regards,
    dogBear


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured