Lecture on the Ternary Operator

Jul 13, 2024

Lecture on the Ternary Operator

Overview

  • The ternary operator, also known as the conditional operator, is a shortcut for if-else statements.
  • Useful for assigning or returning values based on a condition.

Formula

  • Write a condition followed by a question mark (?).
  • If the condition is true, return some_value_if_true.
  • If the condition is false, return some_value_if_false.

Example Usage

Using If-Else Statement

  1. Create a function to find the maximum of two integers.
  2. Function name: find_max with parameters int x and int y.
  3. Logic:
    • Check if x is greater than y.
    • If true, return x.
    • Else, return y.

Code Example

int max = find_max(3, 4); // max will be 4

int find_max(int x, int y) {
    if (x > y) {
        return x;
    } else {
        return y;
    }
}
  1. Changing input values:
    • find_max(5, 4); will return 5.
    • find_max(3, 4); will return 4.

Using Ternary Operator

  1. Simplifies the if-else statement into a single line.
  2. Syntax: condition ? value_if_true : value_if_false

Code Example

int find_max(int x, int y) {
    return (x > y) ? x : y;
}
  1. This code is functionally identical to the if-else example.
  2. Provides a more concise and readable way to return or assign values based on conditions.

Summary

  • The ternary operator is a handy shortcut for if-else statements in assignments or returns.
  • Simply follow the formula: condition ? value_if_true : value_if_false.
  • Can significantly reduce the amount of code for simple conditional logic.

Additional Notes

  • The code examples will be posted in the comment section.
  • Practice this to become familiar with its usage.

Conclusion

  • Ternary operator = less code + more readability.
  • Use it for straightforward conditional value assignments or returns.