ctwos-complementtilde

Complement operator in C


#include<stdio.h>
void main(){
  int i = 3;
  printf("%d", ~i);
}

The output is 2. 3 is 0000 0011. Tilde changes all the bit to their opposite. So how is the answer even 2? As I have read from other posts. 2's complement is (~i)+1 which makes ~ 1's complement operator. Even if it is so how is 2 a possible output?


Solution

  • I doubt the answer it's 2. It should be -4, which is the decimal representation of 11111100.

    Online Run, which outputs:

    -4
    

    Indeed Two's complement is calculated by inverting the digits and adding one. So -4 + 1 = -3, as @WeatherVane commented.


    PS: Unrelated to your question, but the main method typically returns an int, not void. Read more in What should main() return in C and C++?

    Reference: Section 5.1.2.2.1 of the C11 standard (emphasis mine):

    It shall be defined with a return type of int and with no parameters:

    int main(void) { /* ... */ }
    

    or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

    int main(int argc, char *argv[]) { /* ... */ }
    

    or equivalent;10) or in some other implementation-defined manner.

    10) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as char **argv, and so on.

    as @JérômeRichard commented.