Conditional Operator
Part of the Fundamentals section of Coddy's C++ journey — lesson 30 of 74.
The conditional operator is a simple one-line if-else statement. It has the following syntax:
variable = (condition) ? value_if_true : value_if_false;The conditional operator evaluates the condition. If it's true, it assigns value_if_true to the variable; otherwise, it assigns value_if_false.
For example:
int age = 20;
std::string message = (age >= 18) ? "Adult" : "Minor";In this example, since age is greater than or equal to 18, message will be assigned the value "Adult". If age were less than 18, message would be assigned "Minor".
You can stack as many conditions as you like:
vrbl = (cond1) ? val1 : (cond2) ? val2 : val3;For example:
int score = 100;
std::string result = (score == 100) ? "Perfect!" : (score >= 90) ? "Excellent" : "Good";In this example, since score == 100 is true, result will be assigned "Perfect!". If the score were 95, it would be assigned "Excellent".
Challenge
BeginnerCreate a program that checks if a number is positive, negative, or zero using the conditional operator. The program should:
- Take an integer input from the user.
- Use the conditional operator to determine if the number is positive, negative, or zero.
- Print the result in the format:
"The number is [positive/negative/zero]".
Cheat sheet
The conditional operator is a one-line if-else statement with the syntax:
variable = (condition) ? value_if_true : value_if_false;Example:
int age = 20;
std::string message = (age >= 18) ? "Adult" : "Minor";You can stack multiple conditions:
vrbl = (cond1) ? val1 : (cond2) ? val2 : val3;For example:
int score = 100;
std::string result = (score == 100) ? "Perfect!" : (score >= 90) ? "Excellent" : "Good";Try it yourself
#include <iostream>
int main() {
int number;
std::cin >> number;
std::string result = "";
// Write your code below
std::cout << "The number is " << result << std::endl;
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else