Reputation: 1317
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!
Upvotes: 3
Views: 221
Reputation: 399703
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.
Upvotes: 8
Reputation: 1612
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.
Upvotes: 3
Reputation: 108968
The result of an unary-expression with the !
operator is an int
with value 0
or 1
.
Upvotes: 4