#248 Find unintented use of "bitwise and" in boolean expressions

open
nobody
Check (274)
5
2012-10-10
2003-08-06
Daniel Cox
No

The following code snippet is legal Java, but is rarely
what the writer intended.

if (x == 10 & y == 20)
{
...
}

And yes - we did find 3 instances of this in my project's
codebase.

Discussion

  • Lars Kühne

    Lars Kühne - 2003-08-07

    Logged In: YES
    user_id=401384

    Daniel, could you please elaborate on this a bit?

    When exactly is bitwise and "unintended"? Only as the
    toplevel operator in an if/while/... condition? Always if
    both operands are boolean?

    Should other bitwise operators like '|' or the assignment
    variants be covered as well?

     
  • Tim Tyler

    Tim Tyler - 2003-08-07

    Logged In: YES
    user_id=796025

    RFE 754819:

    http://sourceforge.net/tracker/index.php?
    func=detail&aid=754819&group_id=29721&atid=397081

    ...appears to be asking for the same thing.

    A "bitwise and" in this context is "mostly harmless".

    However it fails to type-check the arguments
    to ensure they are boolean - and has different logic
    to the boolean operator in that is always evaluates the RHS.

    The RHS might be a method call with side effects -
    so the resulting program flow can be different.

     
  • Daniel Cox

    Daniel Cox - 2003-08-07

    Logged In: YES
    user_id=662432

    Yes, certainly "bitwise or" should be covered. As far as the
    use of assignment vs equality (= vs. ==), am I mistaken, or
    does the InnerAssignment check cover this? I don't think
    people can be confused about what the other bitwise
    operators do as the characters used are not used in other
    expressions.

    When I submitted the defect I was under the incorrect
    assumption that it was more catastrophic than it really is.
    Tim is correct that the only thing that can really go wrong is
    that it will cause non-short circuit evaluation when you might
    have been expecting it. Of course this is quite insidious...

    I thought (again incorrectly) that the & operator had higher
    precedence and performed promotion from boolean to int,
    therefore resulting in the following expression:

    (x == n == 20)

    where n was the bitwise and of 10 and y.

     

Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks