刚从 K & R
开始,在第 2 章,有一行:
Declarations list the variables to be used and state what type they have and perhaps what their initial values are.
所以:
int x = 42
是一个定义。
和 int x
是一个声明,也是一个定义,因为每个定义都是一个声明.
但是当我们像 K & R
说的那样分配一个初始值时,这不是使声明成为定义吗?
最佳答案
你混淆了两件事:
- 声明声明(声明)对象的*类型、名称和范围是什么
- 定义定义对象的内容是什么
* 对象如:变量、函数等,不是 OOP 对象。
因此,定义通常也是声明,因为如果不说明对象的类型,就无法定义对象中的内容。最容易记住的就是:“每个定义都是声明,但不是每个声明都是定义”
对于变量
只有一种方法可以在不定义变量的情况下进行声明:
extern typeX variable_name
这告诉编译器有一个类型为 typeX 的名为 variable_name 的变量,但不知道从哪里获取它。 声明变量的所有其他方式也是一种定义,因为它告诉编译器为其预留空间并可能为其赋予初始值。
结构和函数的区别更加明显:
对于结构
声明:
struct some_struct{
int a;
int b;
}
这向编译器声明了 some_struct,其中 a 和 b 都是 int 类型的结构变量。
只有当你定义它们时,空间才会被保留,你才能使用它们:
void foo(){
struct some_struct s;
s.a = 1; // For this to work s needs to be defined
}
对于函数:
区别更明显
声明:
// This tells the compiler that there is a function called "foo" that returns void and takes void arguments
void foo();
定义可以像上面的那样(在结构部分)
关于c - 带值变量的定义和声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5118707/