What is meaning of !! in C -- and why is it needed?

1k Views Asked by At

Possible Duplicate:
Double Negation in C++ code

While reading one code I read:

flush = ! !(flags & GST_SEEK_FLAG_FLUSH);

I am not getting what does !! mean here . what does this sentence do?

EDIT:

I got it its a double-negative. trick to convert non-bool data to bool

But what is the need of that? Here flush is bool then if you assign any non zero item to bool it will treat as 1 and zero item as 0 so whats benefit of doing this?

4

There are 4 best solutions below

3
On BEST ANSWER

It's a double-negative. It's a way of converting an otherwise-non-bool expression (such as flags & GST_SEEK_FLAG_FLUSH) to a bool. I personally prefer:

flush = (flags & GST_SEEK_FLAG_FLUSH) != 0;

1
On

Just wanted to add a little example for you that might clear things.

 main()
 {
 int i=10;
 printf("%d",!!i);
 }

Output is 1

0
On

If flush is boolean variable, and you force some non-boolean value to it, some compiler will generate a warning forcing value to bool 'true' or 'false'. So it's safer to use double negation.

0
On

Some compilers (like Visual Studio) will warn when coercing a non-boolean type to an int, for example:

#include <stdio.h>

int main(void) {
    int x = 10;
    bool y = x; // warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)
    return 0;
}

The double-negation trick is one way of converting to bool and preventing this warning, however I would lean towards the != 0 check Jim Buck recommended for clarity.