Hi, How do I access a variable after it has been updated in an if else condition. From searching, it seems as if it is a scoping issue but I thought that declaring a variable prior to the if else would make it available afterwards. For the example below, how can I use the variable `y` after it has been updated within the if else.
I'm sorry for what must be a basic question.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
int main(int argc, constchar **argv) {
int x = 1;
int y ;
if (x==1) {
int y = 10;
std::cout << y << std::endl; // works
} else {
int y = 100;
}
// how to access y after the if else??
std::cout << y << std::endl;
return 0;
}
Oh sorry what I meant was don’t say 'int y = <number>', say 'y = <number>' when you say 'int y' you are making a new y. Instead of using the old predeclared y
#include <iostream>
int main(int argc, constchar **argv) {
int x = 1;
int y ; // you declare a variable called y within the scope of main()
if (x==1) {
int y = 10; // you declare a new y within the scope of if and now ignore the original y
std::cout << y << std::endl; // works
} else {
int y = 100;
}
// how to access y after the if else??
std::cout << y << std::endl; // you access the old y that has not been changed and was ignored up until now
return 0;
}
The minute you enter a different scope, you can no longer see the y in main
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
int main(){
int y = 0;
std::cout << y; // works
function();
return 0;
}
int function(){
std::cout << y; // doesn’t work, y not defined or declared within scope
return 0;
}