C++入门经典-例4.9-输出不同生命周期的变量值

1:代码如下:

// 4.9.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;
void main()
{
    int i,j,k;//此k的生命周期是整个主函数
    cout <<"input the number:" << endl;
    cin >> i >> j;
    k=i+j;
    if( i!=0 && j!=0 )
    {
        int k;//此k的生命周期只在这个if语句内
        k=i-j;
        cout << "k :" << k << endl;        //输出变量K的值
    }
    cout << "k :" <<k << endl;            //输出变量k的值
}
View Code

运行结果:

原文地址:https://www.cnblogs.com/lovemi93/p/7520484.html