auto关键字是C语言中局部变量的默认属性,static关键字指明变量的静态属性,register关键字指明将变量存储在寄存器上.例如:
#include
int main()
{
auto int i = 0;
register int j = 0;
static int k = 0;
return 0;
}
编译通过
*****************************************
auto关键字只能声明局部变量。例如:
#include
auto int g = 0;
register int m = 0;
int main()
{
auto int i = 0;
register int j = 0;
static int k = 0;
return 0;
}
编译错误:文件作用域‘g’的声明指定了auto
*******************************************************************
register不能声明全局变量,用它主要是为了不用访问内存,运行快点。例如:
#include
int g = 0;
register int m = 0;
int main()
{
auto int i = 0;
register int j = 0;
static int k = 0;
return 0;
}
编译错误:‘m’的寄存器名无效
************************************************************************
不能用&获取register变量的地址。例如:
#include
int g = 0;
int m = 0;
int main()
{
auto int i = 0;
register int j = 0;
static int k = 0;
printf("%0x\n",&i);
printf("%0x\n",&j);
printf("%0x\n",&k);
return 0;
}
编译错误:要求寄存器变量‘j’的地址
********************************************************
static变量存储在程序静态区中,只能初始化一次。例如:
#include
int g = 0;
int m = 0;
void f1()
{
int i = 0;
i++;
printf("%d\n",i);
}
void f2()
{
static int i = 0;
i++;
printf("%d\n",i);
}
int main()
{
auto int i = 0;
register int j = 0;
static int k = 0;
for(i=0;i<5;i++)
{
f1();
}
for(i=0;i<5;i++)
{
f2();
}
return 0;
}
running result:
1
1
1
1
1
1
2
3
4
5
*********************************************************************
static修饰的局部变量作用域只是声明的文件中。例如1:
#include
int g = 0;
int m = 0;
extern int test2_g;
void f1()
{
int i = 0;
i++;
printf("%d\n",i);
}
void f2()
{
static int i = 0;
i++;
printf("%d\n",i);
}
int main()
{
auto int i = 0;
register int j = 0;
static int k = 0;
printf("%d\n",test2_g);
return 0;
}
同时编译6_1.c【上面program】、6_2.c运行结果:1
同时编译6_1.c【上面program】、6_3.c不通过:没有申明‘test2_g’
====================6_2.c【下面program】
int test2_g = 1;
====================6_3.c【下面program】
static int test2_g = 1;
例如2:
#include
int g = 0;
int m = 0;
extern int test2_func();
void f1()
{
int i = 0;
i++;
printf("%d\n",i);
}
void f2()
{
static int i = 0;
i++;
printf("%d\n",i);
}
int main()
{
auto int i = 0;
register int j = 0;
static int k = 0;
printf("%d\n",test2_func());
return 0;
}
同时编译7_1.c 【上面program】、7_2.c运行结果是:1
同时编译7_1.c【上面program】、7_3.c编译错误:没有声明test2_func
=========================7_2.c【下面program】
static int test2_g = 1;
int test2_func()
{
return test2_g;
}
========================7_3.c【下面program】
static int test2_g = 1;
static int test2_func()
{
return test2_g;
}
例如3:
#include
int g = 0;
int m = 0;
extern int test2_ff();
void f1()
{
int i = 0;
i++;
printf("%d\n",i);
}
void f2()
{
static int i = 0;
i++;
printf("%d\n",i);
}
int main()
{
auto int i = 0;
register int j = 0;
static int k = 0;
printf("%d\n",test2_ff());
return 0;
}
同时编译8_1.c【上面program】、8_2.c【下面program】,running result: 1
static int test2_g = 1;
static int test2_func()
{
return test2_g;
}
int test2_ff()
{
return test2_func();
}
阅读(1157) | 评论(0) | 转发(0) |