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
true
if bothexpression1
andexpression2
evaluate 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
isAdult
andhasID
are both set totrue
. - The condition
isAdult and hasID
evaluates totrue
because both operands are true. - The
if
block 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
age
is25
, andisStudent
isfalse
. - The condition
age > 18 and age < 30 and not isStudent
evaluates totrue
because all subconditions are satisfied. - The
if
block executes, printing “Eligible for the program.”
Key Points to Remember about and
Keyword
- The
and
keyword is an alternative representation for the&&
operator. - It is part of the alternative tokens provided by C++ to enhance code readability.
- Although functional,
and
is less commonly used than&&
in modern C++ code. - It can be combined with other alternative tokens like
or
andnot
for logical operations.