[C language] the difference between declaration and definition

Foreword:

        Declaration and definition are very important concepts in C language, and they all have their own unique functions in programming. The declaration does not allocate storage space, and the definition allocates storage space. When initializing, the declaration and definition often exist at the same time. This article mainly introduces the basic definition of declaration and definition, analyzes the difference between the two and a large number of code cases.

1. Definition of Declarations and Definitions

        Declaration and definition are two different concepts in C language. In C language, declaration mainly refers to specifying the data type and name of an identifier (variable, function, etc.) in the program in advance, without allocating actual storage space; definition refers to assigning storage space to variables or functions in the program , and initialize it .

For example:

// 声明变量a和函数max,分别表示a是一个int类型的变量,max是一个求两个参数最大值的函数
int a;
int max(int x, int y);

// 定义变量a,分配了4字节的空间,初始值为0
int a = 0;

// 定义函数max,分配代码区域的空间并初始化函数代码
int max(int x, int y) {
    return x > y ? x : y;
}

        In the above code, the first two lines are declarations of variables and functions, the third line is the definition of variables, and the fourth to sixth lines are the definitions of functions.

2. Usage scenarios for declaration and definition

        In the C language, declarations and definitions have their own unique uses, and common usage scenarios include the following aspects.

2.1 Declaring a variable or function

        In a program, if you need to use a certain variable or function, you can declare it in advance. For example:

// 声明变量sum和函数quick_sort
int sum;
void quick_sort(int* nums, int n);

        In this way, other functions or code can use these identifiers by declaring them even before the implementation code of the variable or function definition appears. This is especially important when programs are compiled separately.

2.2 External variables

        When sharing a variable between multiple source files, you can define the variable in one source file and reference the variable declaratively in other files. Such variables are called "external variables".

// file1.c

int count = 0; // 在一个源文件中定义count变量

// file2.c

extern int count; // 引用变量count,表示该变量在其他源文件中已被定义

int main() {
    printf("count = %d", count);
    return 0;
}

        At this point, the compiler will compile the two source files separately to generate an object file, and combine them into one executable file at link time. At this point, the variable  count is considered a global variable.

2.3 Function declaration

        In C language, a function can be defined before another function, but cannot be called before another function. Therefore, if you need to call another undefined function in front of the function, you need to declare the function in advance.

// 函数声明
int max(int x, int y);

// 在另一个函数中调用max函数
int main() {
    int a = 5, b = 10;
    int c = max(a, b); // 调用max函数
    printf("max = %d", c);
    return 0;
}

// 实现max函数
int max(int x, int y) {
    return x > y ? x : y;
}

        In the above code, in order to ensure that  main() the function can call  max() the function normally, it is necessary to declare the function.

2.4 Header files

        In each source file, the same structure definitions, function prototypes, and global variable definitions are often repeated, which leads to redundant code and increased compilation time. Therefore, these repetitive definitions can be extracted and put into a header file to realize code reuse.

        For example, put the above  max() function declaration into a header file:

// max.h
#ifndef MAX_H // 如果没有定义 MAX_H,则执行下面的代码
#define MAX_H // 定义 MAX_H 宏

// 函数声明
int max(int x, int y);

#endif // 结束宏定义

        Then, in  max() the source files that need to use the function, you only need to include the header file.

#include "max.h"

int main() {
    int a = 5, b = 10;
    int c = max(a, b); // 调用max函数
    printf("max = %d", c);
    return 0;
}

// 实现max函数
int max(int x, int y) {
    return x > y ? x : y;
}

        In this way, the function declaration and implementation code can be  max() separated to achieve code reuse and improve compilation efficiency.

3. Notes on declarations and definitions

        There are several important points to note when using declarations and definitions.

3.1 Do not repeat definitions

        In the same scope, a variable or function can only be defined once, but can be declared multiple times. Therefore, when using declarations and definitions, you need to be careful not to duplicate definitions.

// 重复定义变量a
int a = 0;
int a = 1; // error:重复定义a

// 重复定义函数max
int max(int x, int y) {
    return x > y ? x : y;
}
int max(int x, int y) { // error:重复定义max
    return x < y ? x : y;
}

3.2 Scope of declarations and definitions

        In a program, the scope of variables or functions depends on where they are declared and defined.

3.2.1 Global variables and functions

        The declaration and definition scope of global variables and functions is the whole program and can be accessed in any function.

// file1.c

int count = 0; // 在一个源文件中定义count变量

// file2.c

extern int count; // 引用变量count,表示该变量在其他源文件中已被定义

int main() {
    printf("count = %d", count);
    return 0;
}

3.2.2 Local variables and functions

        The scope of local variables and functions is limited to the inside of the block in which they are defined, including code blocks, function bodies, for loops, etc.

void f1() {
    
    int a; // 局部变量a在函数体内可见

    if (1) {
        int b; // 局部变量b在代码块内可见
    }

    for (int i = 0; i < 10; i++) {
        int c; // 局部变量c在for循环内可见
    }
}

void f2() {

    void f3() { // 函数f3仅在函数f2内可见
    }

    f3(); // 在函数f2中可以调用函数f3
}

3.3 Differences between function declaration and definition

        In the C language, there are still some differences between the declaration and definition of functions, which require special attention.

3.3.1 Function declarations must include parameter types

        When declaring a function, you must include the parameter list and the type of each parameter. When defining a function, the parameter list can be empty.

// 函数声明时必须包含参数类型
int max(int x, int y); // 正确
int max(int, int);     // error: 名字重复

// 函数定义时可以省略参数名称
int max(int x, int y) { // 正确
    return x > y ? x : y;
}
int max(int, int) {      // error: 名字重复
    return x > y ? x : y;
}

3.3.2 The number and type of parameters in the function declaration and definition must be consistent.

        In the function declaration and definition, the number and type of parameters must be consistent. Otherwise, the program will compile incorrectly.

// 参数类型不一致
int max(int x, int y); // 函数声明
double max(int x, int y) { // error:函数定义中参数类型与函数声明不一致
    return x > y ? x : y;
}

// 参数个数不一致
int sum(int x, int y);
double sum(int x, int y, int z); // error:函数定义中参数个数与函数声明不一致

// 参数个数和类型一致
int max(int x, int y); // 函数声明
int max(int x, int y) { // 函数定义
return x > y ? x : y;
}

further example

        In order to better understand the use of declarations and definitions in C language , you can further study through the following examples.

Example 1:

// 声明局部变量a和函数max
void max(int x, int y); 
int main() {
    int a = 5, b = 10;
    max(a, b); // 调用max函数
    return 0;
}

// 定义局部变量a和函数max
void max(int x, int y) {
    int a = 0; // 局部变量a在函数max内可见
    a = x > y ? x : y;
    printf("max = %d", a);
}

        In the above code, functions  max() and local variables  are defined a. Functions  max() are called and implemented through declarations in the main function. At this point, local variables  are a only  max() visible within the function.

Example 2:

// 声明全局变量a和函数square
int a;
int square(int x);

int main() {
    
    a = 5; // 对全局变量a进行赋值

    int b = square(a); // 调用函数square
    printf("a = %d, b = %d", a, b);

    return 0;
}

// 定义函数square
int square(int x) {
    return x * x;
}

        In the above code, global variables  a and functions  square() are declared before the main function. In the main function, the global variable  a is assigned the value 5, and then the function is called  square() and passed the parameters  a. At this point, the function  square() uses the parameters  x to calculate and returns the result, and the global variable  a is also updated with its value.

Example 3:

// 声明全局变量count和函数add
extern int count;
int add(int a, int b);

int main() {

    count = 100; // 对全局变量count进行赋值

    int a = 5, b = 10;
    int c = add(a, b); // 调用函数add,并传递参数a和b
    printf("count = %d, c = %d", count, c);

    return 0;
}

// 定义全局变量count和函数add
int count = 0;
int add(int a, int b) {
    count++; // 对全局变量count进行自增操作
    return a + b;
}

        In the above code, global variables  count and functions  add() are declared before the main function. In the main function, the global variable  count is assigned the value 100, then the function is called  add() and passed the parameters  a and  b. At this point, the function  add() uses the passed parameters for calculation and  count increments the global variable. Finally, the function  returns the calculation result, and outputs the global variables  and the calculation result  add() in the main function  .countc

Summarize:

        Declaration and definition are two different concepts in C language, and they play an important role in programming. A declaration can specify the data type and name of an identifier (variable, function, etc.) in advance without allocating actual storage space; a definition assigns storage space to a variable or function and initializes it. When using declarations and definitions, you need to be careful not to repeat definitions; function declarations must contain parameter types; the number and type of parameters must be consistent, etc. A thorough understanding of the principles and usage of declarations and definitions is very important for C language developers.

Guess you like

Origin blog.csdn.net/crr411422/article/details/131033662