The difference between parameters and variables in C language

In C language, there are some obvious differences between parameters and variables when declared and used :

The difference between parameters and variables parameter variable
Declaration method Parameters are declared in the function definition (the parameters are in parentheses after the function name) Variables are declared outside the function (global variables) or inside the function (local variables)
Usage The value passed to the function when the function is called Values ​​that can be used in statements in different locales
life cycle The function parameter life cycle is limited to the function execution period The lifetime of a variable can extend beyond the execution of the function
Scope The scope of function parameters is limited to within the function The scope of a variable can be global or local
How values ​​are passed Function parameters can be passed by value, by pointer, or by reference

Variables can only be passed by value

Example of parameters:

#include <stdio.h>

int sum(int a, int b) 
{ // a和b是函数sum的参数
    return a + b;
}

int main()
 {
    int x = 5, y = 3;
    int result = sum(x, y); // x和y作为参数传入函数sum
    printf("The sum of %d and %d is %d\n", x, y, result);
    return 0;
}

Example of variables:

#include <stdio.h>

int main() {
    int x = 5; // 定义一个变量x并赋值为5
    printf("The value of x is %d\n", x);
    x = 7; // 将变量x的值改为7
    printf("Now the value of x is %d\n", x);
    return 0;
}
 

Summary: Parameters are what is in the brackets after the function name. Variables include global variables and local variables, which are outside and inside the curly brackets respectively.

Guess you like

Origin blog.csdn.net/Aileenvov/article/details/132516652