Clarifying C++ negation

Saturday, 9 December 2000

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.

Tags:

6 comments

You can leave a comment, or trackback from your own site.

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

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

  2. It fits right in with current style of writing on the web: OMG!!! LOL!!!!!!

  3. Another possibility, which fits in with some coding conventions. Use whitespace:

    if ( ! limited) {...}

  4. This advice came up top on google, don’t follow it though, it’s terrible

    Writing !!!condition is almost indistinguishable from !!condition

    and there’s nothing standard about “not” or “and” in c++

  5. @Chris: not, and, xor and a whole bunch of other alternative tokens have been part of C++ since the standard was published in 1998, and possibly even before that. I think the Microsoft compilers didn’t support them until more recently, which may be why they’re not more well-known.

    And I thought it was obvious that !!! is a joke. So just to be clear: it’s a joke.

Leave a comment