C 中的补码运算符

Complement operator in C

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

输出为 2。3 为 0000 0011。波浪号将所有位更改为相反。那么答案是怎么连2呢? 正如我从其他帖子中读到的那样。 2 的补码是 (~i)+1,这使得 ~ 成为 1 的补码运算符。即使是这样,2 怎么可能输出?

我怀疑答案是2,应该是-411111100的十进制表示。

Online Run,输出:

-4

确实Two's complement是把数字倒过来加一算出来的。所以 -4 + 1 = -3,正如@WeatherVane 评论的那样。


PS:与您的问题无关,但 main 方法通常 returns 一个 int,而不是 void。在 What should main() return in C and C++?

中阅读更多内容

参考:Section 5.1.2.2.1 of the C11 standard(强调我的):

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.

正如@JérômeRichard 评论的那样。

  1. 主要功能应该是int main(void)
  2. 答案不只有2-4https://godbolt.org/z/b1GGv8