How is a global variable defined in the C language?
In the C language, global variables are defined by declaring variables outside of any function, anywhere in the program. These variables can be accessed and used throughout the entire program. The method for defining global variables is as follows:
- Variables should be declared outside of all functions, usually at the beginning of the file.
- external
- In functions where global variables are needed, you can simply use the variable name without declaring it again.
Here is an example:
#include <stdio.h>
int globalVariable; // 在所有函数之外声明全局变量
void function1()
{
globalVariable = 10; // 在函数内使用全局变量
printf("Value of globalVariable in function1: %d\n", globalVariable);
}
void function2()
{
globalVariable += 5; // 在另一个函数内使用全局变量
printf("Value of globalVariable in function2: %d\n", globalVariable);
}
int main()
{
function1();
function2();
printf("Value of globalVariable in main: %d\n", globalVariable);
return 0;
}
Output result:
Value of globalVariable in function1: 10
Value of globalVariable in function2: 15
Value of globalVariable in main: 15