在 C++ 中为全局变量赋值

YiL*_*Luo 1 c++ programming-languages

我想知道为什么给全局变量赋值会导致错误

#include <iostream>

using namespace std;

int x = 5;
x = 3; // error: C++ requires a type specifier for all declarations
Run Code Online (Sandbox Code Playgroud)

我不是刚刚在上面的行中声明了吗?好吧,让我们看看 x 是否存在;

#include <iostream>

using namespace std;

int x = 5;
x = 3; // error: C++ requires a type specifier for all declarations
Run Code Online (Sandbox Code Playgroud)

好的,所以它确实同意 x 已定义,但类型“还不是”int。有人可以解释这种行为吗,你怎么称呼这种行为?它是怎么发生的?为什么这样设计?

wal*_*nut 5

x = 3;是一个表达式语句。表达式语句只能出现在块范围内,即在函数体内。

在命名空间范围(全局范围/文件范围)中,您只能有声明/定义,而没有分配。