本文共 3008 字,大约阅读时间需要 10 分钟。
c语言中定义和声明的区别
Mostly beginner programmers are not aware of difference between declaration and definition in C. In this tutorial I will explain the both terms clearly.
大多数情况下,初学者程序员不了解C中的声明和定义之间的区别。在本教程中,我将清楚地解释这两个术语。
It tells compiler about the name and type of the identifier (variable, function, array, etc.). Memory is not reserved in this case.
它告诉编译器标识符的名称和类型(变量,函数,数组等)。 在这种情况下不保留内存。
extern int num;
In above example we declared a variable. It tells the compiler that its name is num and it is of integer type. Space is not allocated for it in memory.
在上面的示例中,我们声明了一个变量。 它告诉编译器其名称为num并且为整数类型。 内存中没有为其分配空间。
Using extern keyword is must while declaring variable in C.
在C中声明变量时必须使用extern关键字。
int add(int, int);
In above example we declared a function. It tells the compiler that function name is add, it takes two arguments and returns a value of integer type.
在上面的示例中,我们声明了一个函数。 它告诉编译器函数名称为add ,它接受两个参数并返回整数类型的值。
Using extern keyword is optional while declaring function. If we don’t write extern keyword while declaring function, it is automatically appended before it.
在声明函数时,使用extern关键字是可选的。 如果我们在声明函数时不写extern关键字,它将自动附加在它之前。
When compiler encounters variable, function, class, etc. declaration then it understands that the definition is somewhere else in the program or any other file.
当编译器遇到变量,函数,类等声明时,它将理解该定义在程序或任何其他文件中的其他位置。
It tells compiler about the working of variable, function (body of function), etc. Memory is reserved in this case.
它告诉编译器变量,函数(函数主体)等的工作。在这种情况下,将保留内存。
int num = 10; //declaration and definition both at a time
In above example we defined a variable and assigned some value to it. Here memory for variable will be allocated.
在上面的示例中,我们定义了一个变量并为其分配了一些值。 此处将分配变量存储空间。
int add(int a, int b){ return a+b;}
In this example we are defining the function i.e. how function add will work.
在此示例中,我们定义了功能,即功能添加的工作方式。
Declaration is really useful in case we defined a function in one file and used it in different files. All we have to do is declare the function in one line in whatever file we have used it.
如果我们在一个文件中定义一个函数并在其他文件中使用它,则声明非常有用。 我们要做的就是在我们使用过的任何文件中的一行中声明该函数。
Note: We can re-declare a variable, function, class, etc multiple times but can define it only once.
注意:我们可以多次重新声明变量,函数,类等,但是只能定义一次。
S.No. | Declaration | Definition |
1 | Tells compiler about name and type of variable, class, function, etc. | Tells compiler about what value stored in variable or working of function, class, etc. |
2 | Memory allocation is not done. | Memory allocation is done. |
3 | Can re-declare multiple times. | Can define only once. |
序号 | 宣言 | 定义 |
1个 | 告诉编译器变量,类,函数等的名称和类型。 | 告诉编译器什么值存储在变量中或函数,类等的工作方式 |
2 | 内存分配未完成。 | 内存分配完成。 |
3 | 可以多次声明。 | 只能定义一次。 |
Comment below if you have queries or found anything incorrect in above tutorial for declaration vs definition.
如果您对上面的声明与定义教程有疑问或发现不正确之处,请在下面评论。
翻译自:
c语言中定义和声明的区别
转载地址:http://zmggb.baihongyu.com/