Thread: Compiler bug or mis-understanding?

  1. #1
    Registered User
    Join Date
    Jun 2003
    Posts
    245

    Question Compiler bug or mis-understanding?

    I've got the following code in a C-style function:

    Code:
    if (disk&0xF0 != 0xF0)
    {
      // code //
    }
    Now this seems fine to me, but the compiler optimizes out the entire 'if' statement without warning. I'm assuming it thinks the statement has no effect.

    If I surround the expression with brackets like so:

    Code:
    if ((disk&0xF0) != 0xF0)
    {
      // code //
    }
    Then the code operates as it should.

    Question is - is this expected behaviour?

  2. #2
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    Bitwise AND(&) has a lower precedence on the C Operator Precedence Table than logical does not equal(!=). Therefore, your original code is equivalent to:
    Code:
    if (disk & (0xF0 != 0xF0))
    {
       // code
    }
    You can see why the compiler takes the liberty of optimizing this out. As you have discovered you can use brackets to force the correct order of evaluation.

    This is similar to the common problem with:
    Code:
    if (hFile = fopen("myfile", "r") == NULL)
    which due to logical equals(==) having precedence over assignment(=) is equivalent to:
    Code:
    if (hFile = (fopen("myfile", "r") == NULL))

  3. #3
    Registered User
    Join Date
    Jun 2003
    Posts
    245
    Thanks for the quick reply, I assumed each side of the == would be evaluated seperately.
    Last edited by _Elixia_; 11-17-2004 at 06:12 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. lcc win32 compiler download problems
    By GanglyLamb in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 08-01-2004, 07:39 PM
  2. OpenScript2.0 Compiler
    By jverkoey in forum C++ Programming
    Replies: 3
    Last Post: 10-30-2003, 01:52 PM
  3. Compiler or OS bug??
    By Frantic in forum C++ Programming
    Replies: 6
    Last Post: 05-20-2003, 11:17 PM
  4. compiler bug ?
    By Spectrum48k in forum C++ Programming
    Replies: 5
    Last Post: 02-25-2003, 09:39 PM
  5. Special Compiler for win app's
    By Unregistered in forum Windows Programming
    Replies: 19
    Last Post: 04-26-2002, 03:52 PM