首页  

c语言中定义和声明的区别     所属分类 c 浏览量 105
difference between declaration and definition in C


Declaration Definition
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.
Memory allocation is not done. Memory allocation is done.
Can re-declare multiple times. Can define only once.

Declaration It tells compiler about the name and type of the identifier (variable, function, array, etc.). Memory is not reserved in this case. 声明 告诉编译器标识符的名称和类型(变量,函数,数组等) 不分配内存 变量声明 Variable Declaration 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关键字 Function Declaration int add(int,int) It tells the compiler that function name is add, it takes two arguments and returns a value of integer type. 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. 当编译器遇到变量,函数,类等声明时,它将理解该定义在程序或任何其他文件中的其他位置 定义 Definition It tells compiler about the working of variable, function (body of function), etc. Memory is reserved in this case. 它告诉编译器变量,函数(函数主体)等的工作。在这种情况下,将保留内存。 变量定义 (Variable Definition) int num = 9; In above example we defined a variable and assigned some value to it. Here memory for variable will be allocated. 定义了一个变量并初始化 , 分配变量存储空间 功能定义 (Function Definition) 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. 可以多次重新声明变量,函数,类等,但是只能定义一次。

上一篇     下一篇
C语言字符串

new和malloc的区别

堆和栈的区别

c语言存储区域和局部变量默认初始值

神奇的js

C/C++常用库及工具