I am trying to assign a variable if one variable equals another value. Here is a simplified version of my problem:
#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; } It outputs the following:
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 Why does variable "b" not stay assigned as 6 once it leaves the if statement? And is there a better way to assign it? In my actual code I have five variables I compare to a.
intfromint b = 6;- then learn about scopeb. The inner scopebhides the first by name. And fyi this invokes undefined behavior regardless, as the outerbis never assigned a value before evaluation during your output insertions.std::endldoes?'\n'ends a line.