Re: using "!!" in "c"




"Keith Thompson" <kst-u@xxxxxxx> wrote in message
news:lnslrlmlv6.fsf@xxxxxxxxxxxxxxxxxx
> "pemo" <usenetmeister@xxxxxxxxx> writes:
> [snip]
>> !! is a good way of turning a scalar value into 1 or 0.
>
> So is (value, 0) (i.e., a comma operator). It turns a scalar value
> into 1 or 0. It just happens to be 0.



What's the point here?



> !! maps 0 to 0, and any non-zero value to 1, for any scalar operand.
>
>> For example, this
>>
>> printf("%p\n", (void *)"boo");
>>
>> will output some value that's not 0, and very unlikely to be 1, e.g.,
>> 0040300



> It will output some implementation-specific sequence of printing
> characters. The sequence may or may not look like a number.

Can you explain this comment too? Is it an allusion to some obscure
minutiae in the std, like "In reality, an implementation is free to encode
an address such that it is displayed in egyptian hieroglyphics"?



>> However, this
>>
>> printf("%p\n", (void *)!!"boo");
>>
>> will output 000001, e.g., '1'
>
> That invokes undefined behavior.
>
> "boo" yields a char* value. The "!" operator yields 1 if its operand
> compares equal to 0, 0 otherwise. In this case, it compares the char*
> value to a null pointer value. Since "boo" cannot be a null pointer,
> !"boo" is guaranteed to yield 0. Applying "!" again yields the int
> value 1.
>
> So the above is equivalent to
>
> printf("%p\n", (void*)1);
>
> The conversion of the int value 1 to void* may yield a trap
> representation; passing this to printf() (or doing anything else with
> it) invokes undefined behavior.


Interesting, so something like this is basically illegal/non-portable now?

void (* n)(void) = (void(*)(void))42;

n();

Years ago I used to use something like the above for invoking interrupt
routines.


.