简体   繁体   中英

Question about C ! operator

My understanding of this is as follows. In C, the ! operator returns 0 if it is given a nonzero value and returns a nonzero value if it is given 0.

Say you have this little snippet of C code:

int y = 0;
int z = !y;

What value will go into z ? Does it simply take !0 to be 1? Is it system dependent? Does the C standard dictate what is supposed to happen? I ran into these questions while doing some homework earlier tonight dealing with bitwise 2's-complement integer manipulation. 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.

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.

Since the ! operator is a logical operator, it will always result in 0 or 1.

So in your case, z will be set to 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 .

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. The expression !E is equivalent to (0==E).

From The C Standard (n1124) section 6.5.3.3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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