如果一个变量等于另一个值,我试图分配一个变量。这是我的问题的简化版本:
#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
为什么变量&#34; b&#34;一旦离开if语句,就不会被分配为6?是否有更好的方式来分配它?在我的实际代码中,我有五个与a。比较的变量。
答案 0 :(得分:2)
您在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;
}
答案 1 :(得分:1)
因为int b = 6;
引入了一个初始化为6的新变量b
。它没有将6设置为外部范围的b
。为此,您应该删除类型说明符:
b = 6;
现在因为b
从未初始化,你有未定义的行为。
答案 2 :(得分:0)
你需要这样做:
int b = 6
答案 3 :(得分:0)
if (a==5)
{
cout << "A equals five" << endl;
b = 6;
cout << "B is this value (if stmt): " << b << endl;
}