-4
#include <stdio.h>

int main() {
    if (~0 == 1)  
        printf("yes\n");
    else
        printf("no\n");
}

why is the if statement false? can anyone explain?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Gajanan
  • 11
  • 3

2 Answers2

1

~ Binary One's Complement Operator is unary and has the effect of 'flipping' bits.

So when you do ~0 == 1 it will check for -1 == 1 which is false

iamdhavalparmar
  • 1,090
  • 6
  • 23
  • Is the result `-1` really guaranteed? – klutt Mar 10 '21 at 07:02
  • 1
    No, it depends on what number you're taking `~` after this operator. – iamdhavalparmar Mar 10 '21 at 07:05
  • 2
    That's certainly true for two complements representation of negative numbers, but that's not the only alternative. – klutt Mar 10 '21 at 07:09
  • 1
    If I'm not wrong, `~0` would yield `0` (or to me more precise `-0`) on a one complement machine and `-INT_MAX` on a machine with signed magnitude representation. – klutt Mar 10 '21 at 07:16
  • I was not wrong. https://en.wikipedia.org/wiki/Signed_number_representations#Comparison_table – klutt Mar 10 '21 at 07:18
-2

~0 is equal to -1, not 1.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • 1
    On a two complement machine, yes. But that's not the only alternative. – klutt Mar 10 '21 at 07:42
  • @klutt: Given https://stackoverflow.com/questions/12276957/are-there-any-non-twos-complement-implementations-of-c, I'm not particularly worried about that. – Bill Lynch Mar 10 '21 at 14:21
  • Yes, it's not very common with other things. But not only is your answer strictly speaking wrong when it's very easy to correct it. It also does not explain at all what the `~` actually does. – klutt Mar 10 '21 at 14:26