Strange behavior with global variables

while i was learning about global variables I did some trials and found one problem. Here goes my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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?
An implementation detail. Your compiler may have optimized your code to use less memory, and thus lets the local and global cows be at the same location.

E.g.

1
2
3
4
5
6
7
8
9
10
11
12
13
void farm1()
{
    int cows; //hm you want an integer here too
    cout<<"in farm1, cows="<<cows<<endl; // you print it
    cows++; // you increment it and never do anything with the value
}

int main()
{
    cout<<"in main, cows="<<cows<<endl; //have used an integer before
    farm1();
    cout<<"back in main, cows="<<cows<<endl;
}


Your compiler may optimize the cows++ out as it doesn't do anything, and puts the local int cows at the same place as the global int cows cause you never actually give a value to cows. Don't rely on stuff like that, how compilers react to undefined situations is completely up to them.

PS: I say may. Of course I have no idea what your compiler really does.
Last edited on
Topic archived. No new replies allowed.