[C language] The usage of global and global variables, how to modify the value of the global variable in the custom function, do not pass it to the formal parameter, just refer to the modification directly

1. Problem background

I recently studied the global variables in the C language and found that unlike the Python language - the global keyword is required to assign values ​​​​to global variables in sub-functions.

In C language, in the main function and custom function, you can directly refer to the global variable, and you can modify it without adding any keywords.

However, during a code execution process, I found that it could not be changed.

code show as below:

#include <stdio.h>

static int a = 1;
static int b = 2;

int add(int x, int y)
{
    
    
    x = 9;
    y = 10;
    printf("%d\n", x+y);
    return x+y;
}


int main()
{
    
    
    add(a, b);
    a = 3;
    b = 4;
    add(a, b);
    printf("%d\n", a);
    printf("%d\n", b);
    return 0;
}

The output is as follows:
insert image description here

Two, the solution

Later, I found out that it was because I passed a and b to the formal parameters, and the global variables were modified through the formal parameters in the custom function (this is not acceptable).

Just change it to the following form.

#include <stdio.h>

static int a = 1;
static int b = 2;

int add(int x, int y)
{
    
    
    a = 9;
    b = 10;
    printf("%d\n", x+y);
    return x+y;
}


int main()
{
    
    
    add(a, b);
    a = 3;
    b = 4;
    add(a, b);
    printf("%d\n", a);
    printf("%d\n", b);
    return 0;
}

The output is
insert image description here

Guess you like

Origin blog.csdn.net/PSpiritV/article/details/130045232