如果一个变量等于另一个值,我正在尝试分配一个变量。这是我的问题的简化版本:
#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
block 中声明了一个新变量。用赋值替换变量声明。
此外,您应该初始化原始的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;
}
关于c++ - 在 If 语句中分配变量 [C++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43665900/