我不明白两者的意义。


当前回答

《K&R》(第二版)中有一些非常明确的定义;这有助于把它们放在一个地方,并作为一个整体来阅读:

"Definition" refers to the place where the variable is created or assigned storage; "declaration" refers to the places where the nature of the variable is stated but no storage is allocated. [p. 33] ... It is important to distinguish between the declaration of an external variable and its definition. A declaration announces the properties of a variable (primarily its type); a definition also causes storage to be set aside. If the lines int sp; double val[MAXVAL] appear outside of any function, they define the external variables sp and val, cause storage to be set aside, and also serve as the declaration for the rest of that source file. On the other hand, the lines extern int sp; extern double val[]; declare for the rest of the source file that sp is an int and that val is a double array (whose size is determined elsewhere), but they do not create the variables or reserve storage for them. There must be only one definition of an external variable among all the files that make up the source program. ... Array sizes must be specified with the definition, but are optional with an extern declaration. [pp. 80-81] ... Declarations specify the interpretation given to each identifier; they do not necessarily reserve storage associated with the identifier. Declarations that reserve storage are called definitions. [p. 210]

其他回答

变量的声明是为了通知编译器以下信息:变量的名称,它持有的值的类型和初始值(如果有的话)。也就是说,声明给出了关于变量属性的详细信息。然而,变量的定义说的是变量存储在哪里。也就是说,变量的内存是在定义变量时分配的。

我最喜欢的例子是int Num = 5这里你的变量是1。定义为int 2。声明为Num和3。实例化值为5。我们

定义对象的类型,可以是内置的,也可以是类或结构。 声明一个对象的名字,这样任何有名字的东西都被声明了,包括变量、函数等。

类或结构允许您在以后使用时更改对象的定义方式。例如

可以声明没有特别定义的异构变量或数组。 在c++中使用偏移量可以定义一个没有声明名称的对象。

当我们学习编程时,这两个术语经常被混淆,因为我们经常同时做这两个。

可执行文件的生成阶段:

(1)预处理器->(2)转换器/编译器->(3)链接器

在第二阶段(译者/编译器),我们代码中的声明语句告诉编译器,这些东西我们将在未来使用,你可以稍后找到定义,意思是:

译者确定:什么是什么?方法声明

(3)阶段(链接器)需要定义来绑定事物

链接器确定:哪里是什么?方法定义

定义:

extern int a;      // Declaration 
int a;             // Definition
a = 10             // Initialization
int b = 10;        // Definition & Initialization

定义将变量与类型关联起来并分配内存,而声明只指定类型而不分配内存。当您希望在定义之前引用变量时,声明更有用。

*不要混淆定义和初始化。两者是不同的,初始化给变量赋值。参见上面的例子。

下面是一些定义的例子。

int a;
float b;
double c;

现在函数声明:

int fun(int a,int b); 

注意函数末尾的分号,所以它表示它只是一个声明。编译器知道在程序的某个地方,该函数将被定义为原型。现在,如果编译器得到一个这样的函数调用

int b=fun(x,y,z);

编译器将抛出一个错误,指出没有这样的函数。因为它没有那个函数的原型。

注意两个程序之间的区别。

程序1

#include <stdio.h>
void print(int a)
{
     printf("%d",a);
}
main()
{
    print(5);
}

其中,print函数也被声明和定义。因为函数调用在定义之后。现在看下一个节目。

项目2

 #include <stdio.h>
 void print(int a); // In this case this is essential
 main()
 {
    print(5);
 }
 void print(int a)
 {
     printf("%d",a);
 }

这是必要的,因为函数调用先于定义,所以编译器必须知道是否有这样的函数。因此,我们声明了一个函数,该函数将通知编译器。

定义:

定义函数的这一部分称为定义。它告诉我们在函数中要做什么。

void print(int a)
{
    printf("%d",a);
}

当您使用extern存储类时,声明和定义的概念将形成一个陷阱,因为您的定义将位于其他位置,而您是在本地代码文件(页面)中声明变量。C和c++之间的一个区别是,在C中,声明通常在函数或代码页的开头完成。在c++中不是这样的。你可以在你选择的地方申报。