Re: using "!!" in "c"
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Wed, 18 Jan 2006 18:28:30 GMT
"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.
!! 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.
> 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.
> I've seen/used !! in functions that allocate memory, and return 1 if the
> memory was allocated ok, else 0.
>
> A routine like this would look something like ...
>
> void * p;
>
> int allocStuff(size_t n)
> {
> p = malloc(n);
>
> return !!p;
> }
That's fine, since !!p is an int value and the function returns an int.
The thing to remember is that !!foo doesn't just normalize foo to 0 or
1; it yields a value of type int, regardless of the type of foo.
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.
- Follow-Ups:
- Re: using "!!" in "c"
- From: pemo
- Re: using "!!" in "c"
- References:
- using "!!" in "c"
- From: markryde
- Re: using "!!" in "c"
- From: pemo
- using "!!" in "c"
- Prev by Date: Re: printf - Can't print "print\my\message"
- Next by Date: Re: using "!!" in "c"
- Previous by thread: Re: using "!!" in "c"
- Next by thread: Re: using "!!" in "c"
- Index(es):
Relevant Pages
|