Back to C++
2026-02-287 min read

Short hand if..else (C++)

Learn Short hand if..else (C++) step by step with clear examples and exercises.

Title: Short Hand if..else (C++)

Why This Matters

The ternary operator in C++ is a powerful tool that simplifies conditional logic and makes your code cleaner, more efficient, and easier to read. By mastering this shorthand if..else statement, you can write better code for competitive coding exams, interviews, and real-world projects.

Prerequisites

Before delving into the ternary operator, ensure you have a strong understanding of the following concepts:

  • Basic C++ syntax, including variables, operators, and control structures like if..else
  • Understanding of functions and function prototypes
  • Familiarity with compilers and how to compile and run C++ programs
  • A good grasp of data types in C++, such as integers, floats, and strings
  • Knowledge of C++ standard library functions and their usage
  • Comprehension of namespaces and the using keyword

Core Concept

The ternary operator in C++ is a shorthand way to write conditional statements. It consists of three operands separated by the question mark (?) and colon (:) symbols. The syntax is as follows:

condition ? expression1 : expression2;

The ternary operator first evaluates the condition. If the condition is true, it returns the value of expression1. Otherwise, it returns the value of expression2. Here's a simple example:

#include <iostream>
using namespace std;

int main() {
int x = 10;
float y = 5.5f;
string result;

(x > 5) ? (result = "x is greater than 5") : (result = "x is less than or equal to 5");

cout << result << endl;

return 0;
}

In this example, the condition (x > 5) evaluates to true because x is indeed greater than 5. As a result, the string "x is greater than 5" is assigned to the variable result. The output will be:

x is greater than 5

Now let's consider a more complex example that involves comparing two floating-point numbers and returning the larger one using both traditional if..else statements and the ternary operator.

#include <iostream>
using namespace std;

int main() {
float num1 = 20.5f, num2 = 15.7f;

// Using if..else
if (num1 > num2) {
cout << "Maximum is: " << num1 << endl;
} else {
cout << "Maximum is: " << num2 << endl;
}

// Using ternary operator
cout << "Maximum using ternary operator is: " << (num1 > num2 ? num1 : num2) << endl;

return 0;
}

In this example, both the if..else statement and the ternary operator produce the same output:

Maximum is: 20.500000
Maximum using ternary operator is: 20.500000

Now, let's dive deeper into the core concept of the ternary operator by exploring more complex examples and best practices.

Ternary Operator Chaining

The ternary operator can be chained to create a sequence of conditional expressions:

(condition1) ? (expression1) : ((condition2) ? (expression2) : ...);

This allows you to perform multiple conditional checks in a single line, making your code more concise. However, it's essential to use proper indentation and parentheses for readability.

Ternary Operator with Multiple Expressions

Although the ternary operator only allows a single expression on the right side, you can return a compound data structure like a struct or a tuple containing multiple values:

#include <iostream>
#include <tuple>
using namespace std;

struct Result {
float maxNum;
bool isMaxFirst;
};

Result getMax(float num1, float num2, float num3) {
Result result;

(num1 > num2 && num1 > num3) ? (result = make_tuple(num1, true)) :
((num2 > num1 && num2 > num3) ? (result = make_tuple(num2, false)) :
(result = make_tuple(num3, false)));

return result;
}

int main() {
float num1 = 20.5f, num2 = 15.7f, num3 = 18.9f;
auto result = getMax(num1, num2, num3);

cout << "Maximum is: " << get<0>(result) << endl;
cout << "Is the first number maximum? " << get<1>(result) << endl;

return 0;
}

In this example, we use a custom struct Result to store both the maximum number and a flag indicating whether it's the first number that is the maximum. The ternary operator is chained to determine the maximum number among three floating-point numbers and return the corresponding Result. We then use the get<0> and get<1> functions from the std::tuple library to access the values in the returned tuple.

Worked Example

Let's consider a more complex example that involves calculating the maximum of four numbers using both traditional if..else statements and the ternary operator. We will also compare their performance using the clock() function.

#include <iostream>
#include <chrono>
using namespace std;

int main() {
float num1 = 20.5f, num2 = 15.7f, num3 = 18.9f, num4 = 22.6f;

// Using if..else
auto start_if = chrono::high_resolution_clock::now();
float maxNumIf = num1;
if (num2 > maxNumIf) maxNumIf = num2;
if (num3 > maxNumIf) maxNumIf = num3;
if (num4 > maxNumIf) maxNumIf = num4;
auto end_if = chrono::high_resolution_clock::now();
auto ifElseTime = chrono::duration_cast<chrono::microseconds>(end_if - start_if).count();

// Using ternary operator
auto start_ternary = chrono::high_resolution_clock::now();
float maxNumTernary = (num1 > num2 && num1 > num3 && num1 > num4) ? num1 :
((num2 > num1 && num2 > num3 && num2 > num4) ? num2 :
((num3 > num1 && num3 > num2 && num3 > num4) ? num3 : num4));
auto end_ternary = chrono::high_resolution_clock::now();
auto ternaryTime = chrono::duration_cast<chrono::microseconds>(end_ternary - start_ternary).count();

cout << "Maximum using if..else is: " << maxNumIf << endl;
cout << "Maximum using ternary operator is: " << maxNumTernary << endl;
cout << "Time taken by if..else: " << ifElseTime << " microseconds" << endl;
cout << "Time taken by ternary operator: " << ternaryTime << " microseconds" << endl;

return 0;
}

In this example, we use the chrono library to measure the time taken by both the if..else statement and the ternary operator to find the maximum of four numbers. The output will include the maximum number found by each method as well as the time taken for each method in microseconds.

Common Mistakes

  1. Forgetting to enclose the condition in parentheses:

Incorrect: if (x > 5) y = 10; else y = 20;

Correct: if ((x > 5)) y = 10; else y = 20;

  1. Placing a semicolon after the condition:

Incorrect: if (x > 5); y = 10;

Correct: if (x > 5) y = 10;

  1. Not properly indenting the expressions:

Incorrect: if (x > 5)y=10;else y=20;

Correct: if (x > 5) {

y = 10;

} else {

y = 20;

}``

  1. Using the ternary operator with incompatible types:

Incorrect: (x > 5) ? "string" : 10;

Correct: int result = (x > 5) ? 1 : 0; or std::string result = (x > 5) ? "string" : "other string";

Common Mistakes (Part 2)

  1. Overusing the ternary operator:

While the ternary operator can make your code more readable and concise in some situations, it's essential to avoid overusing it. In complex multi-condition scenarios, traditional if..else statements might be more appropriate for better readability and maintainability.

  1. Ignoring proper indentation:

Proper indentation is crucial when using the ternary operator, especially in chained or nested conditions, to ensure that your code remains easy to understand and debug.

Practice Questions

  1. Write a program that takes three integers as input and determines whether the first number is greater than, equal to, or less than the second and third numbers using the ternary operator.
  1. Write a program that calculates the maximum of four numbers using the ternary operator.
  1. Write a program that checks if a given year is a leap year using the ternary operator.
  1. Write a program that finds the largest among three floating-point numbers using both traditional if..else statements and the ternary operator, then compare their performance.
  1. Write a program that calculates the factorial of a number using the ternary operator.
  1. Write a program that checks if a given string is a palindrome using the ternary operator.

FAQ

  1. Can I use the ternary operator inside a loop?

Yes, you can use the ternary operator inside loops such as for and while loops.

  1. Can I use the ternary operator with multiple conditions?

No, the ternary operator only supports a single condition. However, you can chain multiple ternary operators to achieve a similar effect, but it's generally recommended to use traditional if..else statements for more complex multi-condition scenarios.

  1. Is there a performance difference between using if..else and the ternary operator?

In most cases, the performance difference between using if..else and the ternary operator is negligible. However, the ternary operator can make your code more readable and concise in some situations.

  1. Is it possible to have multiple expressions on the right side of the ternary operator?

No, the ternary operator only allows a single expression on the right side. If you need to perform multiple operations based on the condition, consider using if..else statements or chaining multiple ternary operators.

  1. Can I use the ternary operator with user-defined functions?

Yes, you can use the ternary operator with user-defined functions as long as they return a compatible type.

  1. Is it possible to have a void expression on the right side of the ternary operator?

No, the right side of the ternary operator must evaluate to a value that can be assigned to a variable or used in an expression. If you need to perform actions without returning a value, consider using if..else statements instead.

Short hand if..else (C++) | C++ | XQA Learn