考虑这个简单的函数
2016-09-26 13:48
183 查看
他以下部分建立在部分1.4b --在局部范围内一看。
当讨论变量时,将范围和持续时间的概念分离出来是很有用的。变量的范围决定了一个变量是可访问的。一个变量的持续时间决定创建和销毁它的地方。这两个概念往往是联系在一起的。
块内部定义的变量称为局部变量。局部变量具有自动持续时间,这意味着它们被创建(和初始化,如果相关)在定义的点,并被破坏时,他们被定义在退出块。局部变量有块作用域(也称为局部作用域),这意味着它们在声明点的范围内输入范围,并且在它们被定义的块的结束时离开范围。
考虑这个简单的函数:
1
2
3
4
5
6
7
8
int main()
{
int i(5); // i created and initialized here
double d(4.0); // d created and initialized here
return 0;
} // i and d go out of scope and are destroyed here
因为我和D是在定义的主要功能块的定义,他们都是被main()执行完毕。
嵌套块中定义的变量将被破坏,只要内部块结束:
int main() // outer block
{
int n(5); // n created and initialized here
{ // begin nested block
double d(4.0); // d created and initialized here
} // d goes out of scope and is destroyed here
// d can not be used here because it was already destroyed!
return 0;
} // n goes out of scope and is destroyed here
当讨论变量时,将范围和持续时间的概念分离出来是很有用的。变量的范围决定了一个变量是可访问的。一个变量的持续时间决定创建和销毁它的地方。这两个概念往往是联系在一起的。
块内部定义的变量称为局部变量。局部变量具有自动持续时间,这意味着它们被创建(和初始化,如果相关)在定义的点,并被破坏时,他们被定义在退出块。局部变量有块作用域(也称为局部作用域),这意味着它们在声明点的范围内输入范围,并且在它们被定义的块的结束时离开范围。
考虑这个简单的函数:
1
2
3
4
5
6
7
8
int main()
{
int i(5); // i created and initialized here
double d(4.0); // d created and initialized here
return 0;
} // i and d go out of scope and are destroyed here
因为我和D是在定义的主要功能块的定义,他们都是被main()执行完毕。
嵌套块中定义的变量将被破坏,只要内部块结束:
int main() // outer block
{
int n(5); // n created and initialized here
{ // begin nested block
double d(4.0); // d created and initialized here
} // d goes out of scope and is destroyed here
// d can not be used here because it was already destroyed!
return 0;
} // n goes out of scope and is destroyed here
void someFunction() { int value(4); // value defined here // value can be seen and used here } // value goes out of scope and is destroyed here int main() { // value can not be seen or used inside this function. someFunction(); // value still can not be seen or used inside this function. return 0; }
相关文章推荐
- 考虑这个简单的函数
- 简单说下COALESCE这个日常使用的函数
- 简单说下COALESCE这个日常使用的函数
- 编写一个函数,返回一个int数组中存储的最大数值,并在一个简单的程序中测试这个函数。(有缺陷)
- 简单问题:用javascript 如何得到明天的这个时候.
- 休息之余简单说下我对“爱情”这个名词的看法
- 如何取得字符点阵数据(GetGlyphOutline函数简单应用)
- 用ASP简单封装了几个函数,使用ServerXMLHTTP把网络上的文件保存到本地服务器.
- 这个家伙糟厉害 函数 这样写!有谁见过这样写的吗?
- 利用LineDDA函数做简单动画
- 一个虚函数的简单例子
- DLL中函数调用简单小例(原创)
- 简单说一下我对这个CRM系统的设计方案哦
- 考虑最复杂的情况,开发出最简单的实现
- 一些比较简单的存储过程的代码,主要是本人对这个东西不太熟,特地写下来!
- [代码复用]至少要考虑下简单的代码复用
- 如何取得字符点阵数据(GetGlyphOutline函数简单应用)
- 这个家伙糟厉害 函数 这样写!有谁见过这样写的吗?
- 简单的获取UNIX系统时间的函数。
- 一个简单用C语言实现的日志函数