/* 变量作用域举例 */
#include <stdio.h>
void a (void); /* 函数原型 */
void b (void); /* 函数原型 */
void c (void); /* 函数原型 */
int x = 1; /* 全局变量 */
main()
{
int x = 5; /* main函数的局部变量 */
printf("local x in outer scope of main is %d \n", x);
{
int x = 7; /* 变量x的新作用域 */
printf("local x in inner scope of main is %d \n", x);
} /* 结束变量x的新作用域 */
printf("local x in outer scope of main is %d \n", x);
a(); /* 函数a拥有自动局部变量x */
b(); /* 函数b拥有静态局部变量x */
c(); /* 函数c使用全局变量 */
a(); /* 函数a对自动局部变量x重新初始化 */
b(); /* 静态局部变量x保持了其以前的值 */
c(); /* 全局变量x也保持其值 */
printf("local x in main is %d \n\n", x);
return 0;
}
void a(void)
{
int x = 25; /* 每次调用函数a时都会对变量x初始化 */
printf("\nlocal x in a is %d after entering a \n", x);
++x;
printf("local x in a is %d before exiting a \n", x);
}
void b(void)
{
static int x = 50; /* 只在首次调用函数b时对静态变量x初始化 */
printf("\nlocal static x is %d on entering b \n", x);
++x;
printf("local static x is %d on exiting b \n", x);
}
void c(void)
{
printf("\nglobal x is %d on entering c \n", x);
x *= 10;
printf("global x is %d on exiting c \n", x);
}
#include <stdio.h>
void a (void); /* 函数原型 */
void b (void); /* 函数原型 */
void c (void); /* 函数原型 */
int x = 1; /* 全局变量 */
main()
{
int x = 5; /* main函数的局部变量 */
printf("local x in outer scope of main is %d \n", x);
{
int x = 7; /* 变量x的新作用域 */
printf("local x in inner scope of main is %d \n", x);
} /* 结束变量x的新作用域 */
printf("local x in outer scope of main is %d \n", x);
a(); /* 函数a拥有自动局部变量x */
b(); /* 函数b拥有静态局部变量x */
c(); /* 函数c使用全局变量 */
a(); /* 函数a对自动局部变量x重新初始化 */
b(); /* 静态局部变量x保持了其以前的值 */
c(); /* 全局变量x也保持其值 */
printf("local x in main is %d \n\n", x);
return 0;
}
void a(void)
{
int x = 25; /* 每次调用函数a时都会对变量x初始化 */
printf("\nlocal x in a is %d after entering a \n", x);
++x;
printf("local x in a is %d before exiting a \n", x);
}
void b(void)
{
static int x = 50; /* 只在首次调用函数b时对静态变量x初始化 */
printf("\nlocal static x is %d on entering b \n", x);
++x;
printf("local static x is %d on exiting b \n", x);
}
void c(void)
{
printf("\nglobal x is %d on entering c \n", x);
x *= 10;
printf("global x is %d on exiting c \n", x);
}
输出:
local x in outer scope of main is 5
local x in inner scope of main is 7
local x in outer scope of main is 5
local x in a is 25 after entering a
local x in a is 26 before exiting a
local static x is 50 on entering b
local static x is 51 on exiting b
global x is 1 on entering c
global x is 10 on exiting c
local x in a is 25 after entering a
local x in a is 26 before exiting a
local static x is 51 on entering b
local static x is 52 on exiting b
global x is 10 on entering c
global x is 100 on exiting c
local x in main is 5