Access a variable after an if else condition

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, const char **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;
}
Last edited on
It does within the scope if it was created within that scope. I suggest declaring y above the if else statement
Thanks highwayman. Sorry I am misunderstanding something, is `y` not already declared above the if else statement.
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main(int argc, const char **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;
}
argh, thank you @highwayman, that has fixed it. So I only need to declare the class once and then I can use it throughout.
Throughout the scope of main yes.
Thanks very much for the explanation, appreciated.
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;
}
Last edited on
Topic archived. No new replies allowed.