1. Local Variables:
A local variable is also called an automatic variable, which declares that at the beginning of a function, it lives on the stack, and its life ends with the function returning.
#include <stdio.h>
int main(void)
{
auto int i = 9; /* 声明局部变量的关键字是auto;因可以省略,几乎没人使用 */
printf("%d\n",i);
getchar();
return 0;
}
2. Global variables:
The global variable declaration is outside the function body and should be in front of the function. Every function can use it, but global variables should be used sparingly.
#include <stdio.h>
void add(void);
void mul(void);
int gi = 3; /* 全局变量 */
int main(void)
{
printf("%d\n",gi); /* 3 */
add();
printf("%d\n",gi); /* 5 */
mul();
printf("%d\n",gi); /* 10 */
getchar();
return 0;
}
void add(void) {
gi += 2;
}
void mul(void) {
gi *= 2;
}
The global variable is initialized to null, and the local variable is a garbage value before it is assigned:
#include <stdio.h>
int gi; /* 全局变量 */
int main(void)
{
int i; /* 句柄变量 */
printf("%d,%d\n",gi,i);
getchar();
return 0;
}
When a global variable has the same name as a local variable, a local variable is used:
#include <stdio.h>
int a = 111,b = 222;
int main(void)
{
int a = 123;
printf("%d,%d\n",a,b); /* 123,222*/
getchar();
return 0;
}