Originally posted by moi
out of curiosity, since b is delcared globally and is also the name of the variable passed to the function, how will it know which b to use?
It will use the one that is most local to it. So :
- in main() when we call prefect(b), the b here is the global one, as is passed by value to prefect().
- in prefect(), we use the local copy of b. Any changes to b here will not affect the global b.
Here's a sample to help explain:
Code:
#include <stdio.h>
int b;
void f(int b)
{
printf ("in func before assignment, b is %d\n", b);
b = 10;
printf ("in func after assignment, b is %d\n", b);
}
int main(void)
{
printf ("in main, b is %d\n", b);
f(b);
printf ("in main after calling func, b is %d\n", b);
return 0;
}
/*
Output:
in main, b is 0
in func before assignment, b is 0
in func after assignment, b is 10
in main after calling func, b is 0
*/