Re: !!, what is it?



"bjk of course" <Use-Author-Supplied-Address-Header@[127.1]> wrote in
message news:20050911144917.GA18115@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
> hello,
>
> I've stumbled upon this in some code:
>
> n = !!x;
>
> I've ran it and 'n' is always either 0 or 1.

Yes, because that's always the result of the ! ("logical not")
operator.

> Is '!!' an operator

No, ! is an operator. It's result is always either zero or one.
It is simply being used twice in the above code. E.g.

!0 == 1
!1 == 0
!42 == 0;
!!42 == 1 /* because !42 == 0, then !(!42) == 1
(because !0 == 1) */


etc.

>(what's it
> called?)

"Logical not".

>and is it standard/portable?

Yes.

int i = 42;
int j = !i; /* initializes 'j' with 0 */
int k; = !!i; /* initializes 'k' with 1 */
int m = !j; /* initializes 'm' with 1 */

The typical reason for this 'double application' of the logical
not operator is to transform a nonzero value (which logically
always evaluates to 'true') into a specific 'true' value (in
this case one (1). The reason for needing to do this depends
upon the application. Here's a simple contrived example:

#include <stdio.h>

/* zero value is invalid, any nonzero value is valid */
void validate(int value)
{
static const char *msg[] = {"invalid", "valid"};
printf("value %d is %s\n", msg[!!i]);
/* note that !!0 always is exactly 0 */
}

int main()
{
validate(42);
return 0;
}

IOW, !42 == 0 , !!42 == 1 , !!42 != 42

If some other specific 'true' value were needed, one would
simply perform more arithmetic upon the value one (e.g. add
some value).

-Mike


.



Relevant Pages