> 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/scope.md).

# 变量作用域

### 全局变量与局部变量

* **全局变量**：定义在所有函数之外，整个程序都可以访问，默认值为 0。
* **局部变量**：定义在函数或语句块内，只在该范围内有效。

```cpp
#include <iostream>
using namespace std;

int g = 10;          // 全局变量

void f() {
    int g = 20;      // 局部变量，遮蔽了全局变量
    cout << g << endl;  // 20
}

int main() {
    cout << g << endl;  // 10
    f();
    {
        int x = 5;   // 仅在花括号内有效
        cout << x;
    }
    // cout << x;    // 错误：x 已失效
    return 0;
}
```

### 作用域与生命周期

|      | 全局变量 | 局部变量   |
| ---- | ---- | ------ |
| 作用域  | 整个文件 | 定义所在的块 |
| 生命周期 | 整个程序 | 块执行期间  |
| 默认初值 | 0    | 不确定    |

### 使用建议

* 尽量少用全局变量，避免命名冲突。
* 大数组开了要清零时，放全局可以自动为 0（也可静态初始化）。
* 局部变量一定要先初始化再使用。


---

# 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/scope.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.
