具有值的变量的定义和声明
刚开始使用 K & R
在第二章中,有这样一行:
声明列出了要声明的变量 使用过并说明它们的类型以及 也许它们的初始值是什么。
所以:
int x = 42
是一个定义。
int x
是一个声明,但也是一个定义,因为每个定义都是一个声明 >。
但是当我们分配一个像 K & 这样的初始值时R
说,这不是使声明成为定义吗?
Just started with K & R
and on the 2nd chapter, there is the line:
Declarations list the variables to be
used and state what type they have and
perhaps what their initial values are.
So:
int x = 42
is a definition.
and int x
is a declaration but also a definition since every definition is a declaration.
But when we assign an intial value like K & R
say, doesn't that make the declaration a definition?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上,您可以说声明只是告诉编译器某处存在具有该名称和类型的变量。它确实会生成任何代码,并且在 C 中,这必须使用变量上的
extern
关键字来完成。函数原型(没有实现)也只是声明,不需要extern
关键字,但您仍然可以提供它。定义生成代码,例如在堆栈或堆上为变量分配内存,或为方法分配主体。
从这个意义上说,你的两个陈述都是定义,任何定义也是一种声明。
我认为这可能是 K&R 的一个错误......
Basically you can say that a declaration simply tells the compiler that there is somewhere a variable with that name and type. It does produce any code, and in C, this has to be done with the
extern
keyword on variables. Function prototypes (without implementation) are also mere declarations, and don't need theextern
keyword, but you can still provide it.A definition produces code, e.g. allocates memory on the stack or heap for a variable, or the body for methods.
In that sense, both of your statments are definitions, and any definition is also a delcaration.
I think that might by a mistake by K&R...
您会混淆两件事:
* 对象如:变量,函数等,而不是 OOP 对象。
因此,定义通常也是声明,因为当您不声明对象的类型时,您无法定义对象中的内容。最容易记住的是:“每个定义都是声明,但并非每个声明都是定义”
对于变量
只有一种方法可以在不定义变量的情况下进行声明:
这告诉编译器有一个变量名为variable_name,类型为typeX,但不知道从哪里获取它。
声明变量的所有其他方式也是一种定义,因为它告诉编译器为其保留空间,并且可能给它一个初始值。
结构和函数的区别更加明显:
对于结构
声明:
这向编译器声明 some_struct,其中 a 和 b 都是 int 类型的结构变量。
仅当您定义它们时,才会保留空间并且您可以使用它们:
对于函数:
区别在于更清晰的
声明:
定义可以类似于上面的定义(在结构部分)
You confuse two things:
* object as in: variable, function etc., not an OOP object.
A definition is hence very often also a declaration, since you cannot define what is in an object when you do not state what the type of the object is. Easiest to remember is just: "Every definition is a declaration, but not every declaration is a definition"
For variables
There is only 1 way to declare without defining the variable:
This tells the compiler that there is a variable called variable_name with type typeX, but not where to get it.
Every other way to declare a variable is also a definition, since it tells the compiler to reserve space for it and perhaps give it an initial value.
The difference is much clearer in structs and functions:
For Structs
A declaration:
This declares some_struct to the compiler with a and b as struct variables both with type int.
Only when you define them space is reserved and you can use them:
For functions:
The difference is much more clear
declaration:
A definition could be like the one above (in the struct part)