This article tries to cover Scope of variable. English meaning of scope is
scope (noun): the extent of the area or subject matter that something deals with or to which it is relevant.
Hence putting simply scope tells what is area of code we could access a variable. Simplest example that we have already seen before is global variables and local variables. Global variables have global scope means they can be accessed from any other place using proper declaration. Local variables are local to the function and can be accessed only in those function. C allows same named variable to be defined in different scope. Lets us understand via this example
#include <stdio.h> extern int a; void f(); void g(); int main() { int a = 10; printf("Value of a in SCOPE_1 is %d\n", a); { int a = 100; printf("Value of a in SCOPE_2 is %d\n", a); } printf("Value of a in SCOPE_1 is %d\n", a); f(); g(); return 0; } void f() { int a = 1000; printf("Value of a in SCOPE_3 is %d\n", a); return; } void g() { printf("Value of a in SCOPE_4 is %d\n", a); return; } int a = 1;
Value of a in SCOPE_1 is 10 Value of a in SCOPE_2 is 100 Value of a in SCOPE_1 is 10 Value of a in SCOPE_3 is 1000 Value of a in SCOPE_4 is 1
Hence in general there are 3 scope
- Global scope - SCOPE_4
- Local function scope - SCOPE_1, SCOPE_3
- Block scope (Local function scope is one of block case) - SCOPE_2
Hope this clarifies the concept of Scope in C Programming.
Links
- Next Article - C Programming #68: Volatile variable
- Previous Article - C Programming #66: Storage Class
- All Article - C Programming
No comments :
Post a Comment