c++ - 在 If 语句中分配变量 [C++]

标签 c++ scope

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

#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/

相关文章:

c++ - 从字符串中删除多余空格的程序

c - 即使在下一次迭代之后,是否在循环中局部声明了一个变量,该循环创建了一个可以在被调用线程中安全使用的线程?

c++ - 插入以设置为 "Fixed"大小循环

c++ - 为什么 std::unique_lock 不是从 std::lock_guard 派生的

javascript - jQuery从点击事件函数中关闭点击事件间隔函数?

c++ - 你能禁止类的本地实例化吗?

C# 变量作用域 : 'x' cannot be declared in this scope because it would give a different meaning to 'x'

JavaScript 将变量值公开

c++ - 是否可以将一个图像放入另一个图像中并始终将其大小调整为特定尺寸?

c++ - 我可以使用 std::vector::insert 向自身插入一个 vector 吗?