我正在学习c++,我在程序中遇到了一个非常奇怪的现象。我还没有看到任何关于这个问题的文档。为什么当我在条件语句中初始化变量时,它在条件语句之外无法识别?变量是条件语句的本地变量吗?
下面是一个示例:
#include "stdafx.h"
#include <iostream>
using namespace std;
/*scope / range of variables */
int global;
int main()
{
int local = rand();
cout << "value of global " << global << endl;
cout << "value of local " << local << endl;
int test = 10;
if (test == 0)
{
int result = test * 10;
}
cout << "result :" << result << endl;
return 0;
}
在这种情况下,结果是不确定的。有人可以解释一下发生了什么吗?
正如注释中指出的,您的result
声明在您提供的if()
块范围内是本地的:
if (test == 0)
{ // Defines visibility of any declarations made inside
int result = test * 10;
} // ^^^^^^
因此声明
cout << "result :" << result << endl;
将导致编译器错误,因为此时在该范围之外,编译器看不到result
。
但是,即使您在作用域块之外正确声明result
,您的逻辑
int result = 0; // Presumed for correctness
int test = 10;
if (test == 0)
{
result = test * 10; // Note the removed declaration
}
没有多大意义,因为test
在根据 You's if()
语句条件中0
的值进行测试之前立即10
给定了该值,并且该条件永远不会变为真。