Re: using "!!" in "c"
- From: "pemo" <usenetmeister@xxxxxxxxx>
- Date: Wed, 18 Jan 2006 16:50:12 -0000
<markryde@xxxxxxxxx> wrote in message
news:1137576503.755112.282840@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
> Hello,
> I saw in some open source projects a use of "!!" in "C" code;
> for example:
> in some header file
> #define event_pending(v) \
> (!!(v)->vcpu_info->evtchn_upcall_pending & \
> !(v)->vcpu_info->evtchn_upcall_mask)
>
> whereas evtchn_upcall_pending is of type unsigned char
> (and also evtchn_upcall_mask is of type unsigned char).
>
> What does "!!" operator do in this case ? Any ideas?
> MR
>
!! is a good way of turning a scalar value into 1 or 0.
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
However, this
printf("%p\n", (void *)!!"boo");
will output 000001, e.g., '1'
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;
}
int main(void)
{
if(allocStuff(...))
{
}
else
{
}
}
Although the code above would work if allocStuff simply returned the actual
pointer value, it would stop someone from finding out that fact, and doing
something like this ...
int main(void)
{
void * p1;
if(p1 = allocStuff(...))
{
// Aha, we've now got a pointer to the memory allocated!!!
}
else
{
}
}
Yes, in the code above [first], you'd also get the same thing by accessing
p, but I hope you get the gist of this simple example, and see how it could
be extended?
.
- Follow-Ups:
- Re: using "!!" in "c"
- From: Flash Gordon
- Re: using "!!" in "c"
- From: Keith Thompson
- Re: using "!!" in "c"
- References:
- using "!!" in "c"
- From: markryde
- using "!!" in "c"
- Prev by Date: Re: make a program using C,C++
- Next by Date: Re: Return value of system
- Previous by thread: Re: using "!!" in "c"
- Next by thread: Re: using "!!" in "c"
- Index(es):
Relevant Pages
|