I was trying to understand the exact meaning of scope in C. What I could understand is that scope is limited to compile time only. For example, in case you access the local variable from some other function. This will result in a compile time error. On the other hand, the following program works fine. This means that the C has a flat memory model and anything can be accessed at run time. C books associate scope with lifetime and variable visibility, I found it quite confusing. I think all these terms makes sense only for the compile time. Can someone please throw light on it?
#include "stdio.h"
int *ptr;
int func(void)
{
/** abc is a local variable **/
int abc = 132;
ptr = &abc;
return 0;
}
int func1(void)
{
/** although scope of abc is over still I can change the value in the address of abc **/
*ptr = 200;
printf("the value of abc=%d\r\n",*ptr);
}
int main(void)
{
func();
func1();
return 0;
}
Results: the value of abc
=200
In the simpler words, what is meant by scope? Does it come into the picture at run time or compile time? As we can see, we can access anything at the run-time. But, if we don't follow the rules, then we will get the compilation error. For example, local variable reference in an another function. The compiler will throw an error saying, "variable not defined...".
Can I say the following about variables?
1) Scope attribute comes under compile time.
2) Lifetime attribute comes under run-time.
3) Visibility attribute comes under compile-time