double negation in C : is it guaranteed to return

2019-01-12 05:17发布

Is !!(x) guaranteed by the standard to return 0/1?

Note that I am not asking about c++, where a bool type is defined.

标签: c standards
2条回答
狗以群分
2楼-- · 2019-01-12 05:45

This is a comment really, but it's too long. (Please don't down vote it on that basis alone.)

I found a very bizarre document while looking for the standard to answer your question: The New C Standard: An Economic and Cultural Commentary. And they say academia is under-funded. (Here is the full, 2083 page 10.5MB PDF. The former link is just the section on double negation.)

It has this to say on the subject of double negation: "A double negative is very often interpreted as a positive statement in English (e.g., “It is not unknown for double negatives to occur in C source”). The same semantics that apply in C. However, in some languages (e.g., Spanish) a double negative is interpreted as making the statement more negative (this usage does occur in casual English speech, e.g., “you haven’t seen nothing yet”, but it is rare and frowned on socially1)."

I believe that the author would be happy knowing that this is of no use whatsoever in answering your real question (the answer to which is yes.)

查看更多
Emotional °昔
3楼-- · 2019-01-12 05:50

Yes, in C99, see §6.5.3.3/4:

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).

So !x and !!y can only yield 0 or 1, as ints.

For other operators, in C99, see also Is the "true" result of >, <, !, &&, || or == defined?

查看更多
登录 后发表回答