+ 1
How can I do this?? Help
Im creating a program that implements a switch case, and I defined some variables in it, but when I try to extract the value of that variable outside the switch I get "variable 'x' might not have been initialized" error. Help pls. Sorry for the bad English I speak spanish
19 Answers
+ 5
Andrés Felipe González Aristizábal first define all the variables in main method of default value.
+ 3
Prathvi thanks, I could fix it with your answer, I had defined the variables but had not given them a value in the main method
+ 2
Could you post your code please?
But it sounds like you try to access a variable outside of its scope. A Scope is defined for example over a compound statement (with {}) and if you declare a variable in this compound statement you can not reach it after the compound statement is closed
+ 2
not initialized:
int x;
initialized:
int x = 0;
If this does not help please share your code.
+ 2
Try defining x outside the switch case! , It may help you plus post the code so we can understand what are you doing wrong.
+ 2
Andrés Felipe González Aristizábal Your Welcome 🌟🌟
+ 2
Hello Piglu
It would be nice if you did not post a sentence but summarized your sentences in one post. ;)
Please keep in mind that everyone who follows this thread will get a notification.
Thank you.
+ 1
You can only reach a variable in its scope. A variable can only be defined once in the current local scope but if you open another and define a variable with the same name you override it in the new scope. But after the new scope is closed you can again reach the original variable.
If you have a lot of scopes opened you can always reach the variables from lower scopes if they are not overwritten
+ 1
So if you define your variable before the switch and initialize it you can use it after the switch
But if you just define and it could be possible that its not initialized in the switch so its maybe not initialized after the switch when you want to use it.
So you at least have to initialize it with some value which will be overwritten in your switch
0
Saransh Agarwal i can't, I need the value of the variable in the switch case
0
Jnn i can reach a variable after the compound statement when is closed? I need to do that how can I change the code?
0
@ I can't reach the value of that variable in a different scope? With a method or something?
0
Make those variables global
0
Then you can access it from any function
0
I edited your code
0
Check it out
0
Sorry about that.... From next time i will keep it in mind