在 If 语句 [C++] 中赋值变量

Assign a Variable in If statement [C++]

本文关键字:赋值 变量 C++ If 语句      更新时间:2023-10-16

如果一个变量等于另一个值,我正在尝试分配一个变量。 这是我问题的简化版本:

#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;
}