C不是运算符应用于int?

2022-01-17 00:00:00 c operators compiler-construction c++

我有

int x = 5;
printf("%d", x); //i get 5... expected

x = !x;
printf("%d", x);// i get 0... hmm 

5 二进制是:0101如果我们对每个位进行逆运算,我们应该得到 1010,但 ! 不一定是反相器,它是一个逻辑运算符.为什么我得到一个 0 ?

5 in binary is: 0101 if we apply the inverse to each bit, we should get 1010, but ! is not necessarily an inverter, it's a logical operator. Why do i get a 0 ?

是因为在 C 中,正数被视为真,所以 !-ing 它会导致 0?这个编译器是特定的吗?

is the reason that, in C, a positive number is treated as true and so !-ing it would result in 0? is this compiler specific?

推荐答案

not (!) 运算符返回 01,分别取决于输入是非零还是 0.

The not (!) operator returns either 0 or 1, depending on whether the input is non-zero or 0 respectively.

如果您正在寻找按位否定,请尝试 ~x.

If you are looking for a bitwise negation, try ~x.

相关文章