> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/basics/ternary.md).

# 三目运算符

### 语法

```
条件 ? 条件为真时的值 : 条件为假时的值
```

它是 `if-else` 的表达式写法，可以返回一个值。

```cpp
int a = 3, b = 5;
int mx = (a > b) ? a : b;    // mx = 5

// 等价于
int mx2;
if (a > b) mx2 = a;
else mx2 = b;
```

### 直接输出

```cpp
cout << (score >= 60 ? "及格" : "不及格") << endl;
```

### 嵌套

```cpp
int grade = score >= 90 ? 4 : score >= 80 ? 3 : score >= 60 ? 2 : 1;
```

嵌套时从右向左结合，但可读性差，建议少用或加括号。

### 注意事项

* 两个分支的**类型要兼容**，否则会按规则隐式转换。
* 不要用 `max`、`min` 做变量名，会和标准库函数冲突：

```cpp
// int max = (a > b) ? a : b;   // 不推荐，遮蔽了 std::max
int mx = (a > b) ? a : b;       // 推荐
```

* 三目运算符优先级较低，复杂表达式要加括号。


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/basics/ternary.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
