12

Possible Duplicate:
Double Negation in C++ code

When I scanned the Webkit source code, I found a strange use of the boolean "not" operator !:

BOOL enabled;
if (SUCCEEDED(sharedPreferences->continuousSpellCheckingEnabled(&enabled)))
    continuousSpellCheckingEnabled = !!enabled;
if (SUCCEEDED(sharedPreferences->grammarCheckingEnabled(&enabled)))
    grammarCheckingEnabled = !!enabled;

Why don't they use enabled directly instead of !!enabled?

Community
  • 1
  • 1
Jiajun
  • 161
  • 5
  • 1
    Nothing here mentions it explicitly, but that `BOOL` is most likely an integer of some sort. Judging by `SUCCEEDED`, I presume winapi, in which it's `int`. – chris Dec 12 '12 at 08:44

5 Answers5

14

It's a C++ trick to convert anything to 1 or 0.

For example, 42 is logically true, but is not 1, so applying !! to it, you turn it into 1.

Luchian Grigore
  • 245,575
  • 61
  • 446
  • 609
5

It's meant to force a value to a boolean. So if the value is evaluating to something, you'll get true.

Grimace of Despair
  • 3,317
  • 25
  • 37
4

It forces a true value to be exactly 1.

In a boolean context (if (x), while (x), x ? a : b, for (; x; )), a value which is 0 means false, while any other value means true.

If your function accepts a truth value, but you need exactly 1 there, !! is fine.

In other words, !!x is the same as x ? 1 : 0.

glglgl
  • 85,390
  • 12
  • 140
  • 213
1

Most probably continuousSpellCheckingEnabled is of type bool. BOOL is defined as int, so:

continuousSpellCheckingEnabled = enabled;

issues a warning, while:

continuousSpellCheckingEnabled = !!enabled;

does not.

Stefan
  • 4,108
  • 2
  • 31
  • 47
1

why don't they directly use "enabled"

Double negation only cancels out for boolean values (0 and 1) so !!(0) == 0 for non-boolean values the value will be converted to boolean !!(100) == 1

iabdalkader
  • 16,363
  • 4
  • 44
  • 70