我的C++变量(范围相关)有什么问题?
What's wrong with my C++ variable(scope related)?
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int x = 0, y = 1, k = 5;
{
int x = 1;
x = 10;
cout << "x is " << x << ", y is " << y << endl;
}
cout << "x is " << x << " and k is " << k << endl;
cout << endl;
cout << endl;
{
int x = 5;
int y = 6;
{
int y = 7;
x = 2;
}
cout << "(x, y) is : (" << x << ", " << y << ")" << endl;
}
cin.get();
return 0;
}
输出为:
x = 10, y = 1
x = 0, k = 5
(x, y) = (2,6)
我认为(x,y)应该是(5,6)。因为这是x和y的坐标
您正在从外部作用域修改x
:
{
int y = 7; // local variable
x = 2; // variable from outer scope
}
如果你说的是int x = 2;
,那么你可以期望得到(5,6)
。但是你没有。
你在最后一个作用域中给x赋值2,因此它是(2,6)。
它不是这样工作的,因为外部作用域的变量x
是您在内部作用域中更改的,其中没有其他x来隐藏它。考虑一下这个例子,为什么这是必要的:
static const size_t N = 10;
size_t i = 0;
int array[N];
while (i < 10) {
const int x = i*i;
array[i] = x;
++i;
} // We're out of the block where i was incremented. Should this be an infinite loop?
// Should array be uninitialized because this is the scope it was in and we updated it in a nested scope?
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 格式说明符C++有什么问题
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 我的堆栈和库存清单程序的结构有什么问题?
- 此工厂功能有什么问题?
- 以下 C++ 代码有什么问题?
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了