0

I am expecting the output to be 10 But i get 11 as per my knowledge while calling fun function, it should take the global variable. ??

#include <iostream>
using namespace first;
int var = 0;

void fun()
{
    cout << var;
}

int main()
{  
    var = 1;
    cout << var;
    fun();
}
Maxim Makhun
  • 2,197
  • 1
  • 22
  • 26

5 Answers5

4

You only declare var once. If you shadow the global variable by a local declaration, the local variable will be used.

For example, see this StackOverflow post for information on how the shadowing works.

Community
  • 1
  • 1
Uli Köhler
  • 13,012
  • 16
  • 70
  • 120
4
int main()
{  
    int var=1;
    cout<<var;
    fun();
}

At the moment you're just modifying the global rather than creating a new one scoped in main().

Then your output will be

10
splrs
  • 2,424
  • 2
  • 19
  • 29
4

You are reassigning the value of 'var' to 1 and then printing 'var' two times. that's why you get 11 as output.

Selva
  • 338
  • 2
  • 12
2

After assigning 1 to var, you are printing 2 times the same variable - note that you aren't creating 2 diffrent variables but you're changing the value of your variable.

enedil
  • 1,605
  • 4
  • 18
  • 34
  • I'm not sure if I unerstand your post correctly, but he is not declaring another var, just changing the value of the global variable. In the specific case above, he won't see 11 because of the specific values used. – Uli Köhler Dec 22 '13 at 16:34
  • Yes, I haven't see that there wasn't int before var = 1 – enedil Dec 22 '13 at 16:36
-1

Var=0 Then var=1 Print var two times Output 11

pavan
  • 34
  • 2
  • 10