> 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/functions/return-and-params.md).

# 函数返回与传参

### 函数的定义与调用

函数把一段可复用的逻辑封装起来。

```cpp
int add(int a, int b) {   // 返回类型 函数名(形参列表)
    return a + b;
}

int main() {
    cout << add(3, 5);    // 调用，实参 3、5
    return 0;
}
```

### 声明与定义分离

函数可以先声明（原型），后定义：

```cpp
int add(int a, int b);   // 声明
// ... main 中使用 ...
int add(int a, int b) { return a + b; }  // 定义
```

### 形参 vs 实参

* **形参**：函数定义中的参数，是局部变量
* **实参**：调用时传入的具体值

### 返回值

* `return` 返回一个值并结束函数
* 无返回值用 `void`
* 函数只能返回一个值，需要多个结果时用引用 / 指针参数带回

```cpp
void minmax(int a[], int n, int &mn, int &mx) {
    mn = mx = a[0];
    for (int i = 1; i < n; i++) {
        if (a[i] < mn) mn = a[i];
        if (a[i] > mx) mx = a[i];
    }
}
```

### 递归函数

函数调用自身，必须有**终止条件**：

```cpp
int fact(int n) {
    if (n <= 1) return 1;      // 终止条件
    return n * fact(n - 1);    // 递归
}
```

### 默认参数与重载（了解）

```cpp
int add(int a, int b = 10) { return a + b; }   // 默认参数
int add(int a, int b, int c) { return a+b+c; } // 函数重载（同名不同参数）
```

> 相关：变量作用域、函数参数传递（值 / 引用 / 指针）。


---

# 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/functions/return-and-params.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.
