while i was learning about global variables I did some trials and found one problem. Here goes my code.

int cows = 10; //global variable

void farm1()
{
    int cows;
    cout<<"in farm1, cows="<<cows<<endl;
    cows++;
}

int main()
{
    //cout<<"in main, cows="<<cows<<endl;
    farm1();
    //cout<<"back in main, cows="<<cows<<endl;
}

Here line 6 prints some garbage value as expected. But when I uncomment lines 12 and 14, line 6 prints 10. Can somebody please explain why?

A variable in a local scope with the same name as a global variable overshadows that variable. cows in farm1 is incremented locally but then destroyed when the function finishes. Try removing line 5 and see what happens.

P.S. It's considered a bad habit to use global variables (except in certain advanced techniques).

thanks jonsca for the reply
I know what you are trying to say. I know if a local variable has the same name as the global variable then the global one will be ignored. I also know local variable will be destroyed while the program exits out of the function.

But my concern is how uncommenting lines 12 and 14 in main function affects the farm1 function.
1. with the comments, line6 prints garbage value
2. without the comments, line6 prints 10.

Yes, I see what you mean, apologies that I misunderstood what you were questioning. I don't have a good answer yet, hehe.

Whatever it is that is causing this behaviour is not standard. When I tried your program, line 6 would output garbage regardless of line 12 and 14 being commented or not, as expected. It might simply be that your compiler puts "cow" from line 12 temporarily on the stack frame of main, than frees that piece of the stack frame, and when you call farm1, the cow variable in farm1 just ends up occupying the same place on the stack and thus has a value of 10. In other words, its just incidental. The expected behaviour is for cow in farm1 to have a garbage value when outputted, it's just that in this case that garbage value ends up being 10 because of what was executed just before the function call. Basically, the 10 is a garbage value.

Try this for example:

#include <iostream>
using namespace std;

int cows = 10; //global variable

void farm1()
{
    int cows;
    cout<<"in farm1, cows="<<cows<<endl;
    cows++;
}

int main()
{
    cout<<"in main, cows="<<cows<<endl;
    farm1();
    farm1();
    farm1();
    farm1();
    farm1();
    cout<<"back in main, cows="<<cows<<endl;
}

See how the garbage value is continuously reused because the local "cow" always takes the same place on the stack frame.

commented: Seems plausible. +7
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.