C++ and Keyword
The and keyword in C++ is an alternative representation for the logical AND operator (&&). It is part of the set of alternative tokens provided by C++ for operators, often used to improve code readability or compatibility with certain keyboard layouts.
The and keyword performs the same logical AND operation as &&, evaluating two expressions and returning true if both expressions are true.
Syntax
</>
Copy
expression1 and expression2;
- expression1
- The first Boolean expression to evaluate.
- expression2
- The second Boolean expression to evaluate.
- The result
- Returns
trueif bothexpression1andexpression2evaluate totrue; otherwise, returnsfalse.
Examples
Example 1: Basic Logical AND with and Keyword
This example demonstrates the use of the and keyword to evaluate two Boolean expressions.
</>
Copy
#include <iostream>
using namespace std;
int main() {
bool isAdult = true;
bool hasID = true;
if (isAdult and hasID) {
cout << "Access granted." << endl;
} else {
cout << "Access denied." << endl;
}
return 0;
}
Output:
Access granted.
Explanation:
- The variables
isAdultandhasIDare both set totrue. - The condition
isAdult and hasIDevaluates totruebecause both operands are true. - The
ifblock executes, printing “Access granted.”
Example 2: Combining Conditions with and Keyword
This example shows how the and keyword can be used with multiple conditions.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int age = 25;
bool isStudent = false;
if (age > 18 and age < 30 and not isStudent) {
cout << "Eligible for the program." << endl;
} else {
cout << "Not eligible for the program." << endl;
}
return 0;
}
Output:
Eligible for the program.
Explanation:
- The variable
ageis25, andisStudentisfalse. - The condition
age > 18 and age < 30 and not isStudentevaluates totruebecause all subconditions are satisfied. - The
ifblock executes, printing “Eligible for the program.”
Key Points to Remember about and Keyword
- The
andkeyword is an alternative representation for the&&operator. - It is part of the alternative tokens provided by C++ to enhance code readability.
- Although functional,
andis less commonly used than&&in modern C++ code. - It can be combined with other alternative tokens like
orandnotfor logical operations.
