Re: Using operator ! twice

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 6/29/07, Luong Ngo <luong.ngo@xxxxxxxxx> wrote:
Hello,

I came across several times codes that use ! operator on an integer
variable. I am curious what is the purpose of using it twice.
For example:

int flag;
               if( !! flag) {
                   //do something
               }


The first ! operator will make !flag to be true if flag is 0, and if
we not again it become false, which is just exactly the same if we
just left it as
   if(flag), since 0 is the same as false. Similar logic for non-0
value of flag. Then why do we need to use ! operator twice to get back
the same value as if we don't use at all? this seems to be the same
for me if we do this in math:  -(-( -8)) = -8;


The reason for using double !s is to evaluate something as a
boolean value. I don't know why use it alone in "if ( !! num )",
but consider this code instead:

char *options[] = { "off" , "on" };

printf("Option is %s.\n", options[!!num]);

Since !!num always evaluates to 0 or 1, you don't have to
test it.


Cheers,
Pedro.

--
Pedro de Medeiros - Ciência da Computação - Universidade de Brasília
Home Page: http://www.nonseq.net - Linux User No.: 234250
-
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html

[Index of Archives]     [Linux Assembler]     [Git]     [Kernel List]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [C Programming]     [Yosemite Campsites]     [Yosemite News]     [GCC Help]

  Powered by Linux