Is !!(x)
guaranteed by the standard to return 0/1?
Note that I am not asking about c++, where a bool type is defined.
In C and C++ the double negation operator can be (and often is) used to convert a value to a boolean. Simply put, if int x = 42 , !! x evaluates to 1. If x = 0 , !!
The double-negation !! is not a distinct JavaScript operator nor a special syntax but rather just a sequence of two negations. It is used to convert the value of any type to its appropriate true or false Boolean value depending on whether it is truthy or falsy.
In the C language, you have several ways to create a negative integer: You can assign a negative value to a variable, you can perform math that results in a negative value, or you can manipulate bits to convert a positive value to a negative one. That final operation isn't as easy as it sounds.
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 int
s.
For other operators, in C99, see also Is the "true" result of >, <, !, &&, || or == defined?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With