在 If 语句 [C++] 中赋值变量
Assign a Variable in If statement [C++]
如果一个变量等于另一个值,我正在尝试分配一个变量。 这是我问题的简化版本:
#include <iostream>
using namespace std;
int main()
{
int a = 5;
int b;
cout << "A is this value (before if): " << a << endl;
cout << "B is this value (before if): " << b << endl;
if (a==5)
{
cout << "A equals five" << endl;
int b = 6;
cout << "B is this value (if stmt): " << b << endl;
}
cout << "B is this value (outside): " << b << endl;
return 0;
}
它输出以下内容:
A is this value (before if): 5
B is this value (before if): 0
A equals five
B is this value (if stmt): 6
B is this value (outside): 0
为什么变量"b"在离开 if 语句后不会一直被赋值为 6? 有没有更好的方法来分配它?在我的实际代码中,我有五个变量与 a 进行比较。
您在if
块中声明了一个新变量。将变量声明替换为赋值。
此外,还应初始化原始b
变量。打印其值而不对其进行初始化会导致未定义的行为。
#include <iostream>
using namespace std;
int main()
{
int a = 5;
int b = 0;
cout << "A is this value (before if): " << a << endl;
cout << "B is this value (before if): " << b << endl;
if (a==5)
{
cout << "A equals five" << endl;
b = 6;
cout << "B is this value (if stmt): " << b << endl;
}
cout << "B is this value (outside): " << b << endl;
return 0;
}
因为int b = 6;
引入了一个新变量b
该变量初始化为 6。它不会将 6 设置为外部作用域的b
。为此,您应该删除类型说明符:
b = 6;
现在b
因为从未初始化过,所以你有未定义的行为。
int main()
{
int a = 5;
int b; // this instance of b has scope over the entire main() function
cout << "A is this value (before if): " << a << endl;
cout << "B is this value (before if): " << b << endl;
if (a==5)
{
cout << "A equals five" << endl;
int b = 6; // this instance of b only exists inside this if statement. As soon as the program leaves this if, this instance of b stops existing
cout << "B is this value (if stmt): " << b << endl;
}
cout << "B is this value (outside): " << b << endl;
return 0;
}
if块内部的int b = 6
带来了范围问题,新变量正在隐藏您在 main 函数中声明的变量
您需要执行以下操作:
if (a==5)
{
cout << "A equals five" << endl;
b = 6;
cout << "B is this value (if stmt): " << b << endl;
}
相关文章:
- 为"adjacent"变量赋值时出现问题
- 非常量变量只读位置的赋值
- 变量在使用赋值语句赋值后恢复为以前的值
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 如何在 c++ 中正确声明/赋值变量的值
- 在未初始化的变量上使用复合赋值运算符(+=, ..)不是C++中的UB?
- c++问题:给一个变量赋值后,另一个变量发生了变化
- 如何在不使用赋值运算符的情况下为动态变量赋值?
- 为什么我不能为变量赋值函数?
- 可视化的c++变量赋值使代码正常工作
- 作为赋值(增加引用变量)C++的左操作数所需的左值
- 如何为结构类型变量赋值
- const变量是否可以在具有默认值的参数中赋值(作为可选参数)
- C++中重载复合赋值运算符不会更改变量
- 初始值设定项列表与构造函数赋值与变量定义
- 在结构的构造函数中使用类方法赋值变量
- 原子变量的多重赋值是原子操作吗?
- 在 If 语句 [C++] 中赋值变量
- 赋值变量时c++未处理异常访问冲突
- 使用reinterpret_cast赋值变量后可能的析构函数