Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solved #510- Storage_Classes.md #529

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions docs/day-10/Storage_Classes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@


# Storage classes in C

A *storage class* in C specifies the scope, lifetime, and initialization behavior of variables. Each variable in C has one storage class. Variables declared within a block have automatic storage by default, unless specified with **`extern`**, **`static`**, or **`register`**.

## Auto Storage Class

The `auto` storage class is used to define local variables within a block. Variables declared as `auto` are automatically initialized with garbage values.

```c
#include <stdio.h>

void main() {
auto int num = 10;
printf("Value of num: %d\n", num);
}
```

## Register Storage Class

The `register` storage class is used to define local variables within a block that are stored in the CPU register for faster access. Modern compilers often optimize register allocation, making explicit use of `register` unnecessary in most cases.

```c
#include <stdio.h>

void main() {
register int count;
for (count = 0; count < 5; count++) {
printf("Count: %d\n", count);
}
}
```

## Static Storage Class

### Static Variable within Function

The `static` storage class is used to define variables that are initialized only once and retain their values between function calls.

```c
#include <stdio.h>

void func() {
static int x = 0;
x++;
printf("x = %d\n", x);
}

void main() {
func();
func();
func();
}
```

### Static Global Variable

```c
#include <stdio.h>

static int count = 5;

void func();

void main() {
while (count--) {
func();
}
}

void func() {
static int i = 5;
i++;
printf("i is %d and count is %d\n", i, count);
}
```

## Extern Storage Class

The `extern` storage class is used to declare a variable that is defined in another file or scope. It extends the visibility of a variable to the entire program.

```c
// File1.c

#include <stdio.h>
extern int count;

void main() {
count = 5;
printf("Count in File1: %d\n", count);
func();
}

// File2.c

#include <stdio.h>
int count;

void func() {
count++;
printf("Count in File2: %d\n", count);
}
```

```