CSO101: Computer Programming
Lecture – 16
O.S.L. Bhavana
Multi-dimensional Arrays
Multi-dimensional arrays as function arguments
Ex: Function declaration: int max(int a[2][3]);
Function call: max(a);
Ex: incorrect function declaration: int max(int a[][]); //second dim missing
Multi-dimensional arrays as function arguments
Storage Classes
Storage Classes
Storage Classes
Feature | Auto | Register | Static | Extern |
Storage | Stack | CPU Register | RAM | RAM |
Initial Value | Garbage | Garbage | Zero | Zero |
Scope | Local | Local | Local | Global |
Lifetime | Block end | Block end | Program end | Program end |
Scope refers to the region of the program where a variable is "visible" or accessible by its name.
Lifetime refers to the duration of time for which a variable remains in the computer's memory during program execution.
Auto
Register
Static Storage Duration
Static Storage Duration: Global Variables
void f(){......}
void g(){......}
main(){....} // variable a can be used by f, g and main
Extern & global variables
int x; // assigns memory for x
int y = 10; //assigns memory for y and sets the value
extern int z; // doesn’t assign memory. Tells the compiler that z is somewhere else (in the header files etc)
int main()
{…..}
int f()
{.....} // both main and f can access x,y,z
All x,y,z are extern storage class variables
Extern
Static Storage Duration: Global Variables
which tells the compiler that there exists a function with name foo and its definition is somewhere else�
Static Storage Duration: Static Keyword
Static Keyword
void f_1(void);
int main( )
{func(); func();func(); } // prints 1,2,3
void func(void)
{
static int count = 1;
printf(“%d\n”, count);
count ++;
}
�
Static Keyword
void f_1(void);
int main( )
{f_1(); f_1();f_1(); } // prints 1,1,1
void f_1(void)
{
static int count = 1; count=1;
printf(“%d\n”, count);
count ++;
}
�
Useful in counting the number of recursive calls a function has
Static Keyword
int fib(int n) //function to print the n^th fibonacci number
{
static int counter = 0;
counter ++;
printf(“In fib with counter = %d \n”, counter);
if (n==0 || n==1) return n;
else return fib(n-2)+ fib(n-1);
}
Number of recursive calls in fib(4)?
�
Shadowing
Variables with same name can exist across different scopes.
int global_var = 60;
void myFunction() {
int x = 10;
static int y = 40; // Outer x
if (1) {
int x = 50; // Inner x (Shadowing)
int y = 50;
int global_var= 50;
printf("%d %d %d ", x,y,global_var);
}
printf("%d %d %d ", x,y,global_var);
}
int main()
{
printf("Hello World");
myFunction();
return 0;
}