在无法识别的情况下初始化的局部变量?
Local variable initialized in a condition not recognized?
我正在学习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()
块 scope 内的本地声明:
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
在根据 if()
语句条件中的值 0
对其进行测试之前立即被赋予了值 10
,条件永远不会变为真。
我正在学习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()
块 scope 内的本地声明:
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
在根据 if()
语句条件中的值 0
对其进行测试之前立即被赋予了值 10
,条件永远不会变为真。