> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/14.-ternary-operator.md).

# 14. Ternary Operator

The ternary operator (`?:`) is a shorthand way to write a simple `if / else` in **one line**. It's the only operator in C++ that takes three parts, which is why it's called "ternary."

```cpp
condition ? valueIfTrue : valueIfFalse;
```

***

### The basic idea — age checker, ternary style

```cpp
#include <iostream>

int main() {
    int age;
    std::cout << "your age: ";
    std::cin >> age;

    std::string result = (age >= 18) ? "welcome to horn pub" : "noobs not allowed";

    std::cout << result << '\n';

    return 0;
}
```

Compare that to the full `if / else` version (topic 11):

```cpp
// if / else — 6 lines
if (age >= 18) {
    std::cout << "welcome to horn pub\n";
}
else {
    std::cout << "noobs not allowed\n";
}

// ternary — 1 line
std::cout << ((age >= 18) ? "welcome to horn pub" : "noobs not allowed") << '\n';
```

Same result, way less typing — but only worth it when the logic is simple. Complex conditions are still clearer as a full `if / else`.

***

### Breaking it down

| Part           | Meaning                                                       |
| -------------- | ------------------------------------------------------------- |
| `condition`    | Anything that evaluates to `true`/`false`, e.g. `age >= 18`.  |
| `?`            | "Then..." — separates the condition from the true-case value. |
| `valueIfTrue`  | What the whole expression becomes if `condition` is `true`.   |
| `:`            | "Else..." — separates the true-case from the false-case.      |
| `valueIfFalse` | What the whole expression becomes if `condition` is `false`.  |

The key thing: **the ternary operator is an expression, not a statement** — it evaluates to a value, so you can assign it directly to a variable, print it, or use it inline.

***

### More cool examples

#### 1. Assigning directly to a variable

```cpp
#include <iostream>

int main() {
    int score = 75;

    std::string status = (score >= 50) ? "Pass" : "Fail";

    std::cout << status << '\n'; // Pass

    return 0;
}
```

#### 2. Finding the max of two numbers (like a mini `std::max`)

```cpp
#include <iostream>

int main() {
    int a = 12, b = 25;

    int biggest = (a > b) ? a : b;

    std::cout << "Biggest: " << biggest << '\n'; // 25

    return 0;
}
```

#### 3. Inline inside `std::cout` (no extra variable needed)

```cpp
#include <iostream>

int main() {
    int num;
    std::cout << "Enter a number: ";
    std::cin >> num;

    std::cout << "That number is " << (num % 2 == 0 ? "even" : "odd") << '\n';

    return 0;
}
```

#### 4. Chaining ternaries (use sparingly — readability drops fast)

```cpp
#include <iostream>

int main() {
    int score;
    std::cout << "Enter score: ";
    std::cin >> score;

    std::string grade = (score >= 90) ? "A"
                       : (score >= 80) ? "B"
                       : (score >= 70) ? "C"
                       : "F";

    std::cout << "Grade: " << grade << '\n';

    return 0;
}
```

> This works, but at 3+ chained ternaries, an `else if` chain (topic 11) is almost always easier to read. Use chaining sparingly.

#### 5. Ternary for a quick sign check

```cpp
#include <iostream>

int main() {
    int num = -8;

    std::string sign = (num >= 0) ? "positive" : "negative";

    std::cout << num << " is " << sign << '\n';

    return 0;
}
```

***

### When to use ternary vs `if / else`

| Use ternary when...                                     | Use `if / else` when...                                        |
| ------------------------------------------------------- | -------------------------------------------------------------- |
| You're picking **one of two values** to assign or print | You need to run **multiple statements**, not just pick a value |
| The condition is simple and easy to read at a glance    | The condition is complex or involves `&&` / \`                 |
| You want a compact one-liner                            | Readability matters more than brevity                          |

***

### Quick Recap

* Syntax: `condition ? valueIfTrue : valueIfFalse;`
* It's a compact alternative to simple `if / else` blocks — an **expression**, not a statement, so it produces a value you can assign or print directly.
* Great for short, single-value decisions (max of two numbers, even/odd, pass/fail).
* Avoid deeply chaining ternaries — past 2 levels, switch back to `if / else if` for readability.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/14.-ternary-operator.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
