Reputation: 27
I am practice with C++ and I see some problem:
#include <iostream>
#include <string>
using namespace std;
int main() {
int a = 2;
{
cout << a;
cout << "\n";
float a = a / 2;
cout << "a= a/2 = ";
cout << a;
}
cout << "\n";
a = 2;
{
cout << a;
cout << "\n";
float b = a / 2;
cout << "b= a/2 = ";
cout << b;
}
}
This return:
2
a= a/2 = 0
2
b= a/2 = 1
I want to know why a = a/2 = 0 ?
Thank you
Upvotes: 0
Views: 103
Reputation: 904
Because you are actually using declared, but never initialized variable when you stated float a = a/2
. My computer prints 4.49985e-039
but that could be any number.
You are confusing yourself because you have two int
& float
variable with same name. Better to choose your name of the variable carefully or you have to track your code to see which is indicating which.
I'll comment on the each line which variable a
has been used.
#include <iostream>
#include <string>
using namespace std;
int main() {
int a = 2; // int a declared in main scope used;
{
cout << a; // int a declared in main scope; since there is no a declared in local scope.
cout << "\n";
float a = a/2; // block scope variable a used without initialization to initialize itself. UB.
cout << "a= a/2 = "; // block scope variable used
cout << a; // block scope variable used
}
cout << "\n"; a = 2; // int a declared in main scope; Since it's block scope is within main scope only.
{
cout << a; // int a declared in main scope; since no a has been declared in local scope
cout << "\n";
float b = a/2; // int a declared in main scope; since no a has been declared in local scope
cout << "b= a/2 = "; // int a declared in main scope; since no a has been declared in local scope
cout << b;
}
}
Upvotes: 2
Reputation: 372664
This is a subtle error. Look at this code:
int a = 2;
{
float a = a / 2;
}
Outside of the curly braces, the name a
refers to int a
, the integer declared up top. But inside the curly braces, once you reach the line in which float a
is declared, the name a
refers to float a
inside the braces rather than int a
outside the braces.
This is a problem because the line
float a = a / 2;
means "create a new variable named a
of type float
. Oh, and it needs an initial value. That's okay! Give it the value of float a
, divided by two." See the problem here? The variable a
is being initialized in terms of itself, so when a / 2
is computed a
has not been initialized and the results are undefined.
To fix this, simply give float a
a new name.
Upvotes: 7