Scope of variables in C language

Variables defined before all functions are global variables, and global variables can be used directly everywhere:

#include <stdio.h>
int a = 100;
void func()
{
    
    
    printf("这里是func:%d\n",a);
}
int main(void)
{
    
    
    func();
    printf("这里是main:%d\n",a);
    return 0;
}

Output result:

这里是func:100
这里是main:100

The scope of use of global variables is: from the definition location to the end of the entire program. example:

#include <stdio.h>
void func()
{
    
    
    printf("这里是func:%d\n",a);
}
int a = 100;
int main(void)
{
    
    
    func();
    printf("这里是main:%d\n",a);
    return 0;
}

At this time, the functionfunc() cannot use variablesa, only main() can use variablesa

Replenish

Within a function, if the name of the defined local variable is the same as the name of the global variable, the local variable will mask the global variable:

#include <stdio.h>
int num = 100;
void func(int num)
{
    
    
    printf("这里是func函数:i = %d\n",num);
}
int main(void)
{
    
    
    func(8);
    printf("这里是main函数:i = %d\n",num);
    return 0;
}

Output result:

这里是func函数:i = 8
这里是main函数:i = 100

Guess you like

Origin blog.csdn.net/YuanApple/article/details/130142948