skip to Main Content

I am using gcc (Ubuntu 13.2.0-23ubuntu4) 13.2.0.

I have a bug in my code where a numerical analysis function is giving very different answers.
Each of the following returns true.

    assert (fpclassify(x) == FP_NORMAL);;
    assert (x == x);
    assert (~(isnan(x)));
    assert (~(isnormal(x)));

I think everything should be single threaded, I don’t think anything is magically changing the value of the variable outside my code. I can’t understand how this could be the case.

Could this be a compiler bug or are here other explanations?

2

Answers


  1. The ~ operator is bitwise complement — it flips all bits of the value — not logical not. So applying it to a "boolean" value will rarely do what you want. For example, the program:

    #include <stdbool.h>
    #include <stdio.h>
    
    int main() {
        if (~true) {
            printf("~true is truen");
        }
    }
    

    will print ~true is true

    Login or Signup to reply.
  2. Each of the issomething floating-point classification macros “returns a nonzero value if and only if its argument” is in the tested category (C 2018 subclauses in 7.12.3). So it does not necessarily produce 0 or 1. It may produce 2, 4, or other numbers.

    When you apply the bitwise complement operator, ~, to these, a zero value will produce a non-zero result, but 1, 2, 4, and most other values will also produce non-zero results; the result will have bits that were on in the operand turned off but bits that were off turned on, usually yielding a non-zero number.

    With two’s complement, only the value equal to ~0, −1, will produce a zero result.

    To test the inverse of isnormal, you can use the Boolean negation: !isnormal(x).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search