Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to know why if we name a variable and name it n and set it to the main function.  Why is the result unpredictable when I call that variable in another block?


What I have tried:

why once the program gave an error and once with random numbers?

#include<iostream>
using namespace std;
int main()
{
	int n=44;
	{
		int n;
		cout<<"n="<<n;
		}		
return 0;	
}
Posted
Updated 26-Apr-20 2:36am
v2
Comments
phil.o 26-Apr-20 7:41am    
Unclear. Please use the green "Improve question" widget and show relevant piece of code.
You may also be interested in reading about variable scope[^].
Nelek 26-Apr-20 8:32am    
OP edited to add content. Please check
phil.o 26-Apr-20 8:38am    
Thanks for the update :)
[no name] 26-Apr-20 8:21am    
And you are sure you defined the variable only once? And not maybe defined it again in a second unit with the same variable name?
Nelek 26-Apr-20 8:33am    
OP edited to add content, please re-check

1 solution

You defined the n variable twice. The former declaration is superseded by the latter. So, when you try to print its value, this is the second declaration which is taken into account. At this point, it has been declared but remains uninitialized; thus, its value is unpredictable, and can be whatever there is at the address the variable is stored.

You can still refer to the link I provided in my comment:
C++ variable scope[^]

And, as a general rule, this is a terrible idea to give the same name to several variables in distinct scopes.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900