C++ not Keyword
The not keyword in C++ is an alternative representation of the logical NOT operator (!).
It is part of the set of alternative tokens introduced to make code more readable and writable, especially in non-English keyboard layouts. The not keyword performs the same operation as !: it inverts the truth value of a Boolean expression.
Syntax
</>
Copy
not expression
- not
- The keyword that inverts the truth value of the expression.
- expression
- The Boolean expression to be negated.
Examples
Example 1: Basic Use of not Keyword
This example demonstrates the equivalence of not and the logical NOT operator (!).
</>
Copy
#include <iostream>
using namespace std;
int main() {
bool isTrue = true;
cout << "Using ! operator: " << (!isTrue) << endl;
cout << "Using not keyword: " << (not isTrue) << endl;
return 0;
}
Output:
Using ! operator: 0
Using not keyword: 0
Explanation:
- The variable
isTrueis initialized totrue. - Both
!isTrueandnot isTruenegate the value ofisTrue, returningfalse(0). - The output confirms that
notis functionally equivalent to the!operator.
Example 2: Using not in Conditional Statements
The not keyword can be used in conditional statements to improve code readability.
</>
Copy
#include <iostream>
using namespace std;
int main() {
bool isAuthenticated = false;
if (not isAuthenticated) {
cout << "Access denied. Please log in." << endl;
} else {
cout << "Welcome!" << endl;
}
return 0;
}
Output:
Access denied. Please log in.
Explanation:
- The
notkeyword is used to check if the value ofisAuthenticatedisfalse. - Since
isAuthenticatedisfalse, theifcondition evaluates totrue, and the corresponding block executes. - The output displays an appropriate message for unauthenticated users.
Example 3: Using not with Logical Operators
The not keyword can be combined with logical operators for complex conditions.
</>
Copy
#include <iostream>
using namespace std;
int main() {
bool isOnline = true;
bool isInMaintenance = false;
if (isOnline and not isInMaintenance) {
cout << "The service is available." << endl;
} else {
cout << "The service is not available." << endl;
}
return 0;
}
Output:
The service is available.
Explanation:
- The condition
isOnline and not isInMaintenanceevaluates totruebecauseisOnlineistrueandisInMaintenanceisfalse. - The corresponding
ifblock executes, indicating that the service is available. - The use of
notimproves readability by clearly expressing the negation.
Key Points to Remember about not Keyword
notis an alternative representation of the logical NOT operator (!).- It inverts the truth value of a Boolean expression.
- It can be used interchangeably with
!, depending on coding style and readability preferences. - It is part of the alternative tokens introduced in C++ to enhance code clarity.
- Using
notcan make complex logical expressions easier to understand.
