【问题标题】:why is the output different when there is no "int" type declaration?为什么没有“int”类型声明时输出不同?
【发布时间】:2017-05-29 15:10:08
【问题描述】:

下面是两个 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”对输出有这样的影响呢?我是新手,非常感谢。

【问题讨论】:

  • 因为范围规则? int a = 3; 声明了一个新变量,a = 3; 引用了之前声明的那个
  • 这不是问题,但您真的需要std::endl 需要的额外内容吗? '\n' 结束一行。

标签: c++ variables scope


【解决方案1】:

因为a = 3; 将现有变量a 设置为值3。int a = 3; 创建了一个新的第三个变量,也称为a 并将那个 初始化为3。原来的变量a 不变。

【讨论】:

  • 谢谢!我还是有点困惑。
猜你喜欢
  • 1970-01-01
  • 2021-10-20
  • 2019-03-14
  • 2012-02-17
  • 2011-04-16
  • 2012-04-14
  • 2020-05-12
  • 2018-01-22
  • 2016-07-03
相关资源
最近更新 更多