考虑这个简单的函数

来源:互联网 发布:机械建模软件 编辑:程序博客网 时间:2024/04/30 10:03
他以下部分建立在部分1.4b --在局部范围内一看。
当讨论变量时,将范围和持续时间的概念分离出来是很有用的。变量的范围决定了一个变量是可访问的。一个变量的持续时间决定创建和销毁它的地方。这两个概念往往是联系在一起的。
块内部定义的变量称为局部变量。局部变量具有自动持续时间,这意味着它们被创建(和初始化,如果相关)在定义的点,并被破坏时,他们被定义在退出块。局部变量有块作用域(也称为局部作用域),这意味着它们在声明点的范围内输入范围,并且在它们被定义的块的结束时离开范围。

考虑这个简单的函数:

12345678int 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;}


0 0