“定义”和“定义”之间的区别和“声明”
可能的重复:
定义和声明之间有什么区别?< /a>
我试图彻底理解C中的“定义”和“声明”。
我相信这里的x
已经被定义了,因为外部变量会自动初始化为0,并且定义了声明和初始化的东西。准确吗?
int x;
main() {}
在本例中根据一个x
是一个定义,但是为什么呢?它没有被初始化...
int print_hello()
{
int x;
}
Possible Duplicate:
What is the difference between a definition and a declaration?
I am trying to thoroughly understand "defining" and "declaring" in C.
I believe x
here is defined, since external variables are automatically initialized to 0, and something that's declared and initialized is defined. Is that accurate?
int x;
main() {}
According to one x
in this case is a definition, but why? It is not being initialized...
int print_hello()
{
int x;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
声明是告诉编译器有一个如下所示的变量。
定义就是告诉编译器这是一个变量。
一是指事物的存在,二是事物本身。
在您的示例中,范围才是造成差异的原因。声明是在文件作用域中进行的,但在块作用域中不可能声明任何内容;因此,第二个例子是一个定义;因为,与
int x;
没有什么关系了。这使得第一个示例(在文件范围内)成为某个
int x;
存在的声明。要从声明中隐藏它,您需要指定为其分配一个值,从而强制分配内存。就像这样:int x = 0;
C 和 C++ 在分析结构时对范围非常敏感。
Declaring is telling the compiler that there's a variable out there that looks like this.
Defining is telling the compiler that this is a variable.
One refers to the existence of a thing, the other is the thing.
In your example, the scope is what makes the difference. Declarations are made in a file scope, but in a block scope it is not possible to declare anything; therefore, the second example is a definition; because, there is nothing left to do with the
int x;
.That makes the first example (in the file scope) a declaration that some
int x;
exists. To covert it from a declaration, you need to specify that a value is assigned to it, forcing the memory allocation. Like so:int x = 0;
C and C++ are very scope sensitive when it is analyzing constructs.
“定义”并不意味着“初始化”。这意味着某些东西被创建,而不仅仅是引用。
定义分配但不一定初始化内存。这可以带来有趣的调试。
"Define" does not mean "initialized." It means something is created, rather than just referenced.
A definition allocates but does not necessarily initialize memory. This can lead to fun debugging.
声明在 TU 中引入名称。定义为该名称实例化/分配存储。
Declaration introduces a name in a TU. Definition instantiates/allocates storage for that name.