C Scope and Storage Classes
Scope tells where a variable can be used. Storage class tells how long it lives and where it is stored.
Local and global variables
| Type | Declared | Can be used | Default value |
|---|---|---|---|
| Local | Inside a function or block | Only in that block | Garbage value |
| Global | Outside all functions | Everywhere after the declaration | 0 |
#include <stdio.h>
int total = 100; // global
void show(void) {
int local = 5; // local to show()
printf("%d %d\n", total, local);
}
int main(void) {
show();
total = 200;
show();
return 0;
}
Output:
Output of the above program is
100 5
200 5
If a local variable has the same name as a global one, the local variable is used inside the function.
Storage classes
| Class | Meaning |
|---|---|
auto | Default for local variables. Created when the block starts and removed when it ends. |
static | Keeps its value between function calls. Initialized only one time. |
extern | Tells that the variable is defined in another file or later. |
register | A hint to keep the variable in a CPU register for speed. The compiler may ignore it. |
static example
#include <stdio.h>
void counter(void) {
static int count = 0;
int normal = 0;
count++;
normal++;
printf("static=%d normal=%d\n", count, normal);
}
int main(void) {
counter();
counter();
counter();
return 0;
}
Output:
Output of the above program is
static=1 normal=1
static=2 normal=1
static=3 normal=1
Note:
Use global variables as little as possible. Many functions can change them, so bugs are hard to find. Prefer passing values as arguments.
Next: C Arrays.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |