问题描述
只是 K&放大器开始; - [R
并在第2章,有一行:
Just started with K & R
and on the 2nd chapter, there is the line:
声明列出变量是
使用和他们有什么类型的国家和
也许什么初始值
所以:
INT X = 42
是定义的
和 INT X
是声明的也是一个的定义的,因为每一个定义的是的声明的
and int x
is a declaration but also a definition since every definition is a declaration.
但是,当我们分配如 K&安培的初值; - [R
说,不,使的声明的一个的定义的?
But when we assign an intial value like K & R
say, doesn't that make the declaration a definition?
推荐答案
您混淆了两件事情:
- 的声明状态(声明的)什么对象的*类型,名称和范围是
- 的定义的定义的什么对象的内容
- A declaration states (declares) what an object's* type, name and scope is
- A definition defines what a object's content is
*对象为:变量,函数等等,而不是一个面向对象的对象
* 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"
对于变量
有只有1个没有定义的变量声明方式:
There is only 1 way to declare without defining the variable:
extern typeX variable_name
这告诉编译器,有一个叫VARIABLE_NAME类型而TYPEx变量,而不是在哪里得到它。
每一个其他的方式来声明一个变量也是一个定义,因为它告诉编译器预留空间,这或许能给它一个初始值。
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:
对于结构
一个声明:
struct some_struct{
int a;
int b;
}
此声明some_struct编译器A和B既是int型的结构变量。
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:
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();
一个定义可能是像上面那样(在结构中的一部分)
A definition could be like the one above (in the struct part)
这篇关于定义和变量声明与某个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!