C++ or Keyword
The or keyword in C++ is an alternative representation of the logical OR operator (||). It is part of the alternative tokens introduced in the C++ Standard to improve code readability and provide an alternative for non-English keyboard layouts.
Like ||, the or keyword evaluates to true if at least one of its operands evaluates to true. If both operands evaluate to false, the result is false.
Syntax
</>
Copy
expression1 or expression2
- or
- The keyword representing the logical OR operation.
- expression1, expression2
- The operands being compared. These should evaluate to Boolean values.
Examples
Example 1: Basic Use of or Keyword
This example demonstrates the equivalence of or and the logical OR operator (||).
</>
Copy
#include <iostream>
using namespace std;
int main() {
bool a = true;
bool b = false;
cout << "Using || operator: " << (a || b) << endl;
cout << "Using or keyword: " << (a or b) << endl;
return 0;
}
Output:
Using || operator: 1
Using or keyword: 1
Explanation:
- The variables
aandbaretrueandfalse, respectively. - Both
a || banda or bevaluate totrue, as at least one operand istrue. - The output confirms that
oris functionally identical to||.
Example 2: Using or in Conditional Statements
The or keyword can be used in conditional statements for logical comparisons.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 10;
if (x == 5 or y == 20) {
cout << "At least one condition is true." << endl;
} else {
cout << "Both conditions are false." << endl;
}
return 0;
}
Output:
At least one condition is true.
Explanation:
- The first condition
x == 5evaluates totrue. - The second condition
y == 20evaluates tofalse. - Since one condition is true, the
oroperator results intrue, and theifblock executes.
Example 3: Combining or with Logical AND
The or keyword can be combined with logical and or not for complex conditions.
</>
Copy
#include <iostream>
using namespace std;
int main() {
bool isOnline = true;
bool isInMaintenance = false;
bool isAdmin = false;
if ((isOnline or isAdmin) and not isInMaintenance) {
cout << "Service is accessible." << endl;
} else {
cout << "Service is not accessible." << endl;
}
return 0;
}
Output:
Service is accessible.
Explanation:
- The condition
(isOnline or isAdmin)evaluates totruebecauseisOnlineistrue. - The condition
not isInMaintenanceevaluates totruebecauseisInMaintenanceisfalse. - Both conditions together result in
true, and theifblock executes.
Key Points to Remember about or Keyword
oris an alternative representation of the logical OR operator (||).- It evaluates to
trueif at least one of its operands evaluates totrue. - It is functionally identical to
||and can be used interchangeably. - It is part of the alternative tokens introduced to improve readability and support different keyboard layouts.
- Using
oris optional and depends on coding style or preference.
