📅  最后修改于: 2020-10-22 01:20:59             🧑  作者: Mango
C语言中的存储用于确定变量的生存期,可见性,内存位置和初始值。 C中有四种类型的存储
Storage Classes | Storage Place | Default Value | Scope | Lifetime |
---|---|---|---|---|
auto | RAM | Garbage Value | Local | Within function |
extern | RAM | Zero | Global | Till the end of the main program Maybe declared anywhere in the program |
static | RAM | Zero | Local | Till the end of the main program, Retains value between multiple functions call |
register | Register | Garbage Value | Local | Within the function |
#include
int main()
{
int a; //auto
char b;
float c;
printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c.
return 0;
}
输出:
garbage garbage garbage
#include
int main()
{
int a = 10,i;
printf("%d ",++a);
{
int a = 20;
for (i=0;i<3;i++)
{
printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
}
}
printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
}
输出:
11 20 20 20 11
#include
static char c;
static int i;
static float f;
static char s[100];
void main ()
{
printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
}
输出:
0 0 0.000000 (null)
#include
void sum()
{
static int a = 10;
static int b = 24;
printf("%d %d \n",a,b);
a++;
b++;
}
void main()
{
int i;
for(i = 0; i< 3; i++)
{
sum(); // The static variables holds their value between multiple function calls.
}
}
输出:
10 24
11 25
12 26
#include
int main()
{
register int a; // variable a is allocated memory in the CPU register. The initial default value of a is 0.
printf("%d",a);
}
输出:
0
#include
int main()
{
register int a = 0;
printf("%u",&a); // This will give a compile time error since we can not access the address of a register variable.
}
输出:
main.c:5:5: error: address of register variable ?a? requested
printf("%u",&a);
^~~~~~
#include
int main()
{
extern int a;
printf("%d",a);
}
输出量
main.c:(.text+0x6): undefined reference to `a'
collect2: error: ld returned 1 exit status
#include
int a;
int main()
{
extern int a; // variable a is defined globally, the memory will not be allocated to a
printf("%d",a);
}
输出量
0
#include
int a;
int main()
{
extern int a = 0; // this will show a compiler error since we can not use extern and initializer at same time
printf("%d",a);
}
输出量
compile time error
main.c: In function ?main?:
main.c:5:16: error: ?a? has both ?extern? and initializer
extern int a = 0;
#include
int main()
{
extern int a; // Compiler will search here for a variable a defined and initialized somewhere in the pogram or not.
printf("%d",a);
}
int a = 20;
输出量
20
extern int a;
int a = 10;
#include
int main()
{
printf("%d",a);
}
int a = 20; // compiler will show an error at this line
输出量
compile time error