Alternative Tokens in C++
You can use not instead of ! in C++
I found some unusual code in C++.
That was like:
bool ok = true;
if (not ok)
{
// ...
}
Normally, C++ code would look like this, using ! as the logical NOT operator:
if (!ok)
{
// ...
}
However, not is also valid. This is called an alternative token.
The following are defined as alternative tokens:
| Keyword | Defined as |
|---|---|
| and | && |
| and_eq | &= |
| bitand | & |
| bitor | |
| compl | ~ |
| not | ! |
| not_eq | != |
| or | |
| or_eq | |
| xor | ^ |
| xor_eq | ^= |
In C, these are defined as macros in iso646.h, so you can use them by including that header.
Similar Features
Similar features include digraphs and, already removed in C++17, trigraphs.
Digraphs
| Keyword | Defined as |
|---|---|
| <: | [ |
| :> | ] |
| <% | { |
| %> | } |
| %: | # |
Trigraphs
| Keyword | Defined as |
|---|---|
| ??= | # |
| ??/ | \ |
| ??' | ^ |
| ??( | [ |
| ??) | ] |
| ??! | |
| ??< | { |
| ??> | } |
| ??- | ~ |
About Using These
Basically, you don’t need to use these. They are not commonly used, and they require readers to have detailed knowledge, so you shouldn’t use them unless necessary.
However, I can understand the argument that not is more readable than !.
Comparison with Perl
In Perl, you can use both not and !, but their precedence is different. Keyword-style operators like not have lower precedence than symbol-style operators like !.
So Perl programmers sometimes write code like this:
if (not $isSaturday || $isSunday) {
# Processing for weekdays
}
This has the same meaning as:
if (!($isSaturday || $isSunday)) {
# Processing for weekdays
}
By using precedence, you can omit parentheses.
In other words, in Perl, predicates connected by symbols form a block, and keyword-style operators modify that block.
The not keyword in C++ is just an alternative to !, so there is no such precedence difference.