Logical Operators: and
Sometimes one condition isn't enough. “If it's Friday and it's warmer than 20 °C, I'll go out” is made of two conditions joined by the word “and”. In C++, that's the operator && (two & characters in a row). Read it as “and”:
std::string day = "Friday";
int temperature = 25;
if (day == "Friday" && temperature > 20) {
std::cout << "I'm going out" << std::endl;
}This prints:
I'm going out&& is a logical operator: it joins two conditions into one. The joined condition is true only if both parts are true. If even one of them is false, the whole condition is false:
true && trueistruetrue && falseisfalsefalse && trueisfalsefalse && falseisfalse
You can join more conditions in a row: a && b && c is true only if all three are true.
Each part must be a complete comparison. “Age from 13 to 19” is age >= 13 && age <= 19. If you shorten it the way we speak, to age >= 13 && <= 19, the compiler reports error: expected expression, because it doesn't know what <= 19 should compare. The math notation 13 <= age <= 19 doesn't work either. For that one, the compiler reports error: chained comparison 'X <= Y <= Z' does not behave the same as a mathematical expression: chaining comparisons like this doesn't mean in C++ what it means in math.
Instructions
- 1
Write an
ifstatement that printsWelcomeonly ifusernameis"admin"and at the same timepasswordis"kitten42". Join the two comparisons with&&. - 2
Add an
elsebranch that printsWrong username or password. Then try a wrong password: changepasswordto"kitten". One false part is enough to make the whole condition false, so the program printsWrong username or password.