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.
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:
using namespace std;
int cows = 10; //global variable
cout<<"in farm1, cows="<<cows<<endl;
cout<<"in main, cows="<<cows<<endl;
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.
I have a 2d matrix with dimension (3, n) called A, I want to calculate the normalization and cross product of two arrays (b,z) (see the code please) for each column (for the first column, then the second one and so on).
the function that I created to find the ...
Write a C program that should create a 10 element array of random integers (0 to 9). The program should total all of the numbers in the odd positions of the array and compare them with the total of the numbers in the even positions of the array and indicate ...