“定义”和“定义”之间的区别和“声明”

发布于 2024-10-06 17:41:00 字数 588 浏览 9 评论 0原文

可能的重复:
定义和声明之间有什么区别?< /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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一花一树开 2024-10-13 17:41:00

声明是告诉编译器有一个如下所示的变量。

定义就是告诉编译器这是一个变量。

一是指事物的存在,二是事物本身。

在您的示例中,范围才是造成差异的原因。声明是在文件作用域中进行的,但在块作用域中不可能声明任何内容;因此,第二个例子是一个定义;因为,与 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.

你的笑 2024-10-13 17:41:00

“定义”并不意味着“初始化”。这意味着某些东西被创建,而不仅仅是引用。

定义分配但不一定初始化内存。这可以带来有趣的调试。

"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.

闻呓 2024-10-13 17:41:00

声明在 TU 中引入名称。定义为该名称实例化/分配存储。

int x; //definition,also a declaration. Every definition is a declaration.
int main(){}

Declaration introduces a name in a TU. Definition instantiates/allocates storage for that name.

int x; //definition,also a declaration. Every definition is a declaration.
int main(){}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文