您的位置:首页 > 编程语言 > C语言/C++

C/C++中关于声明变量时4种存储类的简单介绍

2010-07-19 16:41 495 查看
C/C++语言中,可以通过存储类修饰符来告诉编译器将要处理的是什么类型的变量。

存储类有以下4种:自动(auto)、 静态(static)、 外部(extern)、 寄存器(register)。

1.自动存储类(auto):

#include <iostream>

// Function prototype.
void DisplayTitle();

////////////////////////////////////////
// The main() function.
////////////////////////////////////////
int main()
{
// auto storage-class specifier.
auto int Amount = 500;

DisplayTitle();
std::cout << Amount;

return 0;
}

////////////////////////////////////////
// A function that executes during
// the variable Amount's lifetime.
////////////////////////////////////////
void DisplayTitle()
{
// main()'s Amount exists,
// but is not in scope here.
std::cout << "Amt = ";
}


运行结果:



说明:

anto存储类修饰符指定一个局部变量为自动的,这意味着每次执行到定义该变量的语句块时,都将在内存中为该变量产生一个新的副本,并对其进行初始化。实际上,如果不特别指明,局部变量的存储类默认为自动的,因此,加不加auto关键字都可以。

2.静态存储类(static):

#include <iostream>

// Function prototype.
int Gather();

////////////////////////////////////////
// The main() function.
////////////////////////////////////////
int main()
{
int gwool = 0;
while (gwool < 60)
{
gwool = Gather();
std::cout << gwool << std::endl;
}
}

////////////////////////////////////////
// Return the current value of the wool
// static variable.
////////////////////////////////////////
int Gather()
{
// A static local variable.
static int wool = 50;

return ++wool;
}


运行结果:



说明:

static存储类修饰符指定一个局部变量为静态的。尽管静态局部变量的作用域仍然仅限于声明他的语句块中,但在语句块执行期间,变量将始终保持它的值。而且,初始化值只在语句块第一次执行时起作用,在随后的运行过程中,变量将保持语句块上一次执行时的值。

3.外部存储类(extern):

////////////////////////////////////////
// File Name: pr05008a.cpp
////////////////////////////////////////
#include <iostream>

// Function prototype.
void AccumulateAmount(void);

////////////////////////////////////////
// The main() function.
////////////////////////////////////////
int main()
{
// A variable declared as external.
extern float Amount;

AccumulateAmount();
std::cout << Amount;

return 0;
}


////////////////////////////////////////
// File Name: pr05008b.cpp
////////////////////////////////////////

// Definition of the external variable.
float Amount;

////////////////////////////////////////
// Set the value of the Amount variable.
////////////////////////////////////////
void AccumulateAmount()
{
Amount = 5.72;
}


运行结果:



说明:

extern存储类修饰符声明的是程序将要用到的但又尚未定义的外部变量。通常,外部存储类都用于声明在另一个转换单元中定义的变量。

4.寄存器存储类(register):

#include <iostream>

////////////////////////////////////////
// The main() function.
////////////////////////////////////////
int main()
{
// A register variable declaration.
register unsigned int Counter;

for (Counter = 100; Counter < 1000; Counter += 50)
std::cout << "Counter: " << Counter << endl;

return 0;
}


运行结果:



说明:

除了程序无法得到他的地址外,声明为寄存器存储类的变量和自变量一样。

使用寄存器存储类的目的是把某个局部变量存放在计算机的某个硬件寄存器中而不是主存中以提高程序的运行速度。不过,这只反映了程序员的主观意愿,编译器可以忽略register存储类修饰符。但是即便最后变量被存放在可设定地址的内存中,无法取得地址的限制依然存在。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: