Reputation: 1
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.
Upvotes: 0
Views: 355
Reputation: 48258
int b = 6
inside of the if block is bringing a scope problem, the new variable is shadowing the variable you declared in main function
you need to do:
if (a==5)
{
cout << "A equals five" << endl;
b = 6;
cout << "B is this value (if stmt): " << b << endl;
}
Upvotes: 0
Reputation: 812
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;
}
Upvotes: 0
Reputation: 36463
Because int b = 6;
introduces a new variable b
that's initialized to 6. It doesn't set 6 to the b
of the outer scope. To do that, you should remove the type specifier:
b = 6;
Right now because b
is never initialized you have undefined behaviour.
Upvotes: 1
Reputation: 780724
You declared a new variable inside the if
block. Replace the variable declaration with an assignment.
Also, you should initialize the original b
variable. Printing its value without initializing it results in undefined behavior.
#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;
}
Upvotes: 2