Storage Classes in C
Storage Classes in C
#include<stdio.h>
void func() {
auto int x = 1;
printf("%d\n", x);
x += 1;
}
int main() {
func();
func();
return 0;
1
}
Output
1
1
In this example, the 'x' variable is declared as 'auto'. Each time
the 'function()' is called, the value of 'x' is initialised to 1,
incremented by one, and then it goes out of scope once the
function ends. Calling the function multiple times will not retain
the previous value of 'x'.
2
x += 1;
}
int main() {
func();
func();
return 0;
}
classes
The `static` storage class has a dual role. First, when used with
local variables, it enables the variables to retain the value
between function calls. These static local variables are initialised
only once, no matter how many times the function is called.
Secondly, when used with global variables or functions, it
restricts their scope to the file they are declared in. The main
properties of `static` storage class are:
3
void func() {
static int x = 1;
printf("%d\n", x);
x += 1;
}
int main() {
func();
func();
return 0;
}
Output
Value of x: 1
Value of x: 2
In this example, the 'x' variable is declared with the 'static'
storage class inside the 'function()'. Although the variable is local
to the function, its value is retained between function calls. As a
result, when we call the 'function()' multiple times, the value of 'x'
is incremented and keeps track of the number of times the
function has been called.
The `extern` storage class is used to tell the compiler about the
existence of a variable or a function that is defined in another
program (file). The primary aim of using the `extern` storage
class is to access and share these external variables or functions
across different program files. Here are the main features of the
`extern` storage class:
4
Using the `extern` keyword with a variable or a function ensures
that its storage is not allocated multiple times. It also prevents
errors and ambiguities that may arise from redeclaring these
variables or functions in different program files.
EXTERNAL STORAGE CLASS
Definition and Example of External Storage Class
External storage class in C, represented by the keyword
'extern', is used to give a reference of a global variable
that is visible to all program files. When a variable is
declared with the 'extern' keyword, it indicates that the
variable is defined in another file and the current file is
using its reference.
#include<stdio.h>
int x; // x is a global variable
void func() {
extern int x; // x is referenced here
printf("%d\n", x);
x += 1;
}
int main() {
x = 1;
func();
func();
return 0;
}
Output:
1
2
5
Ex1.c
#include”other.c”
#include<conio.c>
Other.c
6
7