当没有“int”类型声明时,为什么输出不同?

时间:2017-05-29 15:10:09

标签: c++ variables scope

以下是两个C ++代码:

#include <iostream>
using namespace std;

    int a = 1;

int main()
{
    int a = 2;

    if(1)
    {
            a = 3;
            cout << a << endl;
    }
    cout << a << endl;
}

输出是: 3 3

#include <iostream>
using namespace std;

    int a = 1;

int main()
{
    int a = 2;

    if(1)
    {
            int a = 3;
            cout << a << endl;
    }
    cout << a << endl;
}

输出为:3 2

这两个代码是相似的,只是第二个代码在“a = 3”之前有“int”。那么,为什么“int”对输出有这样的影响呢?我是新手,非常感谢。

1 个答案:

答案 0 :(得分:0)

因为a = 3;将现有变量a设置为值3. int a = 3;创建一个新的第三个变量,也称为a并初始化 到3.原始变量a未更改。