zoukankan      html  css  js  c++  java
  • c++之变量的生存期及可见性

     1 #include <iostream>
     2 using namespace std;
     3 
     4 //变量的生存期及可见性
     5 int i = 1;    // i全局变量具有静态生存期
     6 void other(){
     7     static int a = 2;
     8     static int b;        //变量a和b为静态局部变量,具有全局寿命,但是只有在本函数中可见,
     9                         //并且只有当函数第一次被调用时,a和b才会被创建,意思就是说上面两
    10                         //句话,只可能被执行一次,当你下一次调用这个函数时a和b的值还是上一次
    11                         //的最终值。
    12     int c = 10;        //c为局部变量,具有动态生存期,每次调用函数时都会进行初始化。
    13     a += 2;    c +=2;    i += 2;
    14     cout << "--->other---" << endl;
    15     cout << "a:" << a << "c:" << c << "i:" << i << endl;
    16     b = a;
    17 }
    18 
    19 void main(){
    20     static int a;        //a为静态局部变量,具有全局寿命,局部可见,初始化时如果没有赋值,则系统自动赋值为零;
    21     int b = -10;
    22     int c = 0;                //b和c为局部变量,具有动态生存期,必须赋值才能使用。
    23     cout << "--->main---" << endl;
    24     cout << "a:" << a << "b:" << b << "c:" << c << "i:" << i << endl;
    25     c += 8;
    26     other();
    27     cout << "--->main---" << endl;
    28     cout << "a:" << a << "b:" << b << "c:" << c << "i:" << i << endl;
    29     i += 10;
    30     other();
    31 }
  • 相关阅读:
    【洛谷P1119】灾后重建
    【洛谷P1462】通往奥格瑞玛的道路
    【洛谷P1991】无线通讯网
    poj 2892(二分+树状数组)
    hdu 1541(树状数组)
    hdu 5059(模拟)
    hdu 5056(尺取法思路题)
    poj 2100(尺取法)
    hdu 2739(尺取法)
    poj 3320(尺取法)
  • 原文地址:https://www.cnblogs.com/Smart-Du/p/4316857.html
Copyright © 2011-2022 走看看