need help

what is the output the c++ code shown above?

my answer is 10_10, why is it wrong? Both a=20 and b=b+5 are local variables, ringht?

1
2
3
4
5
6
7
8
9
  int a=5;
  int b=10;
  a = a+5;
  {int a;
   a=20;
   b=b+5;
  }
  cout<<a<<"_"<<b<<endl;
In line 4 you are declaring a new variable called a in a new scope, as such the outer one will be hidden until the block completes. So when a is assigned 20, once the block ends it will be lost and line 8 will refer to the first a which is 10. Btw, your output is 10_15.

You shouldn't use names twice like that, and if you do any nested ones will hide the outer ones.
Last edited on
thx a bunch!
Topic archived. No new replies allowed.