Clarifying C++ negation

The C++ negation operator (!) can be hard to see in code listings, and this leads to bugs. Here are a few solutions to this perennial coding problem.

The C negation operator (!) is used by most C++ programmers also. The trouble with it is that it can be hard to see. For example, code like this

if (!limited) {...}

can be confusing, as it’s easy to miss the exclamation mark when skimming the code. Some people get around this by using

if (limited==false) {...}

but many other people think this is ugly, unnatural and verbose. (I am one of these people.) Such people often desert C++ for a !-less language like Python. But if you insist on C++, not all is lost. Standard C++ offers a neat solution:

if (not limited) {...}

Much prettier than limited==false and much more visible than !limited. And so clear, even a non-programmer could understand it. If your compiler doesn’t support these alternative keywords (not instead of !, and instead of &&, etc.), you could always use #define. (Of course, the #define trick works in C as well.)

Postscript: Another solution to the visibility problem just occurred to me, late at night. This is particularly good since it works in C, Java, and probably any other language that uses !.

if (!!!limited) {...}

Evaluating the utility of this approach is left as an exercise to the reader.

Share This | Comments | Permalink | Trackback | Comments feed

3 responses

  • [...] l for clarity and visibility in code, I recommend prefix operators over postfix. (See also Clarifying C++ negation.) [...]
  • if (!!!limited) {…}

    You’re joking right? My eyes hurt just looking at all those exclamation marks.

    Simon | 30 March 2006
  • It fits right in with current style of writing on the web: OMG!!! LOL!!!!!!

    Bennett | 30 March 2006

Post a comment

(required)
(required)
Close
E-mail It