Storage
Storage
Classes &
Scope
{
register int miles;
}
• The register should only be used for variables that require quick
access such as counters. It should also be noted that defining
'register' does not mean that the variable will be stored in a register.
It means that it MIGHT be stored in a register depending on
hardware and implementation restrictions.
static
• The static storage class instructs the compiler to keep
a local variable in existence during the life-time of the
program instead of creating and destroying it each
time it comes into and goes out of scope.
main() {
while(count--)
{
func();
}
return 0;
}
/* function definition */
void func( void )
{
static int i = 5; /* local static variable */
i++;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
Global Variable
• Global variables are defined outside of a function,
usually on top of the program.
int main () {
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
Example
• A program can have same name for local and global
variables but value of local variable inside a function will
take preference.
#include <stdio.h>
/* global variable declaration */
int g = 20;
int main () {
/* local variable declaration */
int g = 10;
printf ("value of g = %d\n", g);
return 0;
Formal Parameter
• Function parameters, so called formal
parameters, are treated as local variables within
that function and they will take preference over
the global variables.
Example
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}