Sunday, September 8, 2013

Scope, lifetime and Visability in C

 http://www.linuxforu.com/2011/10/joy-of-programming-scope-lifetime-and-visibility-in-c/


There are five scopes in C: program, file, function, block, and prototype.


void foo() {}
// "foo" has program scope
static void bar() {
    // "bar" has file scope
    printf("hello world");
    int i;
    // "i" has block scope
}
void baz(int j);
// "j" has prototype scope
print:
// "print" has function scope

All non-static functions have program scope, and they can be called from anywhere in the program.

Of course, to make such a call, the function needs to be first declared using extern, before being called, but the point is that it is available throughout the program.

 There are three lifetimes in C: static, automatic and dynamic.

Summery of differences

As you can see, scope, lifetime and visibility are related to each other, but are distinct. Scope is about the ‘availability’ of the declared variable: within the same scope, it is not possible to declare/define two variables of the same type with the same name. Lifetime is about the duration in which the variable is ‘alive’: it determines how long the named or unnamed variable has memory allocated to it.
Visibility is about the ‘accessibility’ of the declared variables: it arises because of the possibility of variables in outer scope having the same name as the ones in inner scopes, resulting in ‘hiding’.

No comments:

Post a Comment