OPERATORS for logical not
You can choose whether you want to write ! , or not , or some kind of mixture.
However, as of version 10.0, Visual C ++ still does not have the reserved word not .
So, for Visual C ++, if you want to use not , you must include the header [ iso646.h ], which is the header from the C standard library, guaranteed to be available in C ++ as well. However, for the standard C ++ compiler that includes this header, it does not work (as indicated in footnote 176 of the C ++ 11 standard). So you can just turn it on anyway:
#include <iostream> #include <iso646.h> // Visual C++ is not quite standard and requires this. int main() { using namespace std; // Display false and true as "false" and "true": cout << boolalpha; cout << "!false = " << !false << endl; cout << "not false = " << not false << endl; }
ON COMPARING Boolean Values:
Some newbies write things like
v != true
This is not just a verbose, but a completely dangerous habit. The reason this is dangerous is because many APIs define logical types where the possible values ββare not limited to only 0 and 1 (the main example is the Window & rsquo; s BOOL ). Then the value can mean the logical value True, without being numerically equal to True.
So, for maximum safety, use the habit ! or not , and just donβt compare directly with a literal boolean value.
An example where it is usually necessary to compare logical values ββis where you need a logical Xor (exclusive or, or-or). In C ++, there is no operator for this at the BOOL level. But you can write a != b to achieve the same as the hypothetical BOOL level operator Xor.
Logical Xor as a CONTROLLED INVERSION
In some cases, you need an inversion (logical Not application) if some condition is true, for example & hellip;
if( condition ) { x = !x; }
Otherwise, it can be written as & hellip;
x = ((condition) != x);
It looks like a complete obfuscation, but it has two functions that may be useful in certain situations:
it can be used as a kind of "masked" inversion for an array a values ββwith the values ββof some other array, which serves to control the inversion of each element a and
it is a calculation of a pure expression that does not include the choice of the execution path, and therefore it can apparently be used as optimization (however, I understand that the modern compiler will probably do this for you at the level of machine code, if appropriate).
Cheers and hth.,