Tuesday, April 1, 2008

Scope, Lifetime of a Variable

Storage classes in C:-

Storage classes in C resolve 2 important coding issues Scope, lifetime of a variable :

· Scope: Which lines of code can see/use this variable?

· Lifetime: Where is it born? die? (memory allocation/de-allocation)

· It is very important to have clear ideas of these two fundamental concepts

Key words that define storage classes are :

auto

register

static

extern

What is a local variable or local scope?

A variable is local when it is visible to the code block where it is born - local scope

E.g auto, static variables have local scope

What is global scope?

A variable is global when it is visible to all the code in the program. Global variables declared above main( )

E.g: extern

auto default

local scope

initialized to some garbage value

E.g. : auto int a ;

static: local scope

initialized to 0 if not initialized

advantage: Retain values between function calls

E.g.: static int a ;

register: local scope

stored in CPU registers

Advantage: fast processing ( useful in loop counters)

E.g.: register int a ;

extern : Global scope. The variable is defined elsewhere in another file. This program merely declares it and is using it

E.g. : extern int a ;

main( )

{

----

}

Global variable: A variable declared above main( ) is called a global variable

scope : All lines of code

lifetime : throughout the program

global is not a key word.

No comments: