简体   繁体   English

关于C的问题! 操作者

[英]Question about C ! operator

My understanding of this is as follows. 我对此的理解如下。 In C, the ! 在C中, ! operator returns 0 if it is given a nonzero value and returns a nonzero value if it is given 0. 如果给定非零值,则运算符返回0,如果给定0,则返回非零值。

Say you have this little snippet of C code: 假设您有这段C代码:

int y = 0;
int z = !y;

What value will go into z ? 什么价值将进入z Does it simply take !0 to be 1? 是否只需要!0为1? Is it system dependent? 它是系统依赖的吗? Does the C standard dictate what is supposed to happen? C标准是否规定了应该发生的事情? I ran into these questions while doing some homework earlier tonight dealing with bitwise 2's-complement integer manipulation. 我在今晚早些时候做一些功课时遇到了这些问题处理按位2的补码整数操作。 I got a certain problem to work, but I'm sort of scratching my head as to why it works. 我有一个问题需要解决,但是我有点不知道为什么它会起作用。 Thanks a lot for any info! 非常感谢任何信息!

Truth values "generated by" C are always 0 or 1. “由C生成的真值”始终为0或1。

It is true (heh) that a non-zero expression is generally considered "true" in if and so on, but when the language itself needs to generate a truth value it uses 0 for false and 1 for true. 这是事实(港灯),在一个非零的表达通常被认为是“真” if等,但在语言本身需要产生一个真值,它使用0假,1为真。

Since the ! 自从! operator is a logical operator, it will always result in 0 or 1. operator是一个逻辑运算符,它总是会产生0或1。

So in your case, z will be set to 1. 所以在你的情况下, z将被设置为1。

Update : See this FAQ entry for more discussion, that's what I had in mind with the "generated by" wording. 更新 :有关更多讨论,请参阅此常见问题解答条目 ,这就是我对“生成的”措辞所记录的内容。 Amazingly, it even has the same pun (I did not look this entry up before writing my answer). 令人惊讶的是,它甚至有相同的双关语(在写我的答案之前我没有看到这个入口)。 Not sure if this is an indication of me having a good sense of humor, or not. 不确定这是否表明我具有良好的幽默感。

The result of an unary-expression with the ! 与一元表达的结果! operator is an int with value 0 or 1 . operator是一个值为01int

The result of the logical negation operator ! 逻辑否定运算符的结果! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. 如果其操作数的值比较不等于0则为0;如果其操作数的值比较等于0则为1.结果的类型为int。 The expression !E is equivalent to (0==E). 表达式!E等价于(0 == E)。

From The C Standard (n1124) section 6.5.3.3. 来自C标准(n1124)第6.5.3.3节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM