Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Ibrahim Assignment

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

University of karachi

Introduction to Computer & Programming


Course No. 305

Name Muhammad Ibrahim

Course 305

Course Incharge Dr. Ambreen Insaf

Department Applied physics


Storage Classes in C
We use the storage class in the C language for determining the visibility, lifetime, initial value, and
memory location of any given variable. The storage classes define the visibility (scope) and the lifetime of
any function/ variable within a C program. These classes precede the type that they are going to modify.

Table of Contents
 Types Of Storage Classes In C
 Use Of Storage Class In C
 Summary Of Storage Classes In C
 Automatic Storage Class
 External Storage Class
 Static Storage Class
 Register Storage Class

Types of Storage Classes in C


There are four different types of storage classes that we use in the C language:

 Automatic Storage Class


 External Storage Class
 Static Storage Class
 Register Storage Class

Use of Storage Class in C


A variable given in a C program will have two of the properties: storage class and type. Here, type refers to
any given variable’s data type, while the storage class determines that very variable’s lifetime, visibility,
and also its scope.
Summary of Storage Classes in C

Class Name of Place of Scope Default Lifetime


Class Storage Value

auto Automatic RAM Local Garbage Within a function


Value

extern External RAM Global Zero Till the main program ends. One can declare it
anywhere in a program.

static Static RAM Local Zero Till the main program ends. It retains the available
value between various function calls.

register Register Register Local Garbage Within the function


Value
1. `auto` Storage Class:

In C, the auto storage class is the default storage class for variables declared within a block or function. Variables
with the auto storage class are automatically created and initialized each time the block or function is entered and
destroyed when the block or function is exited. Here are three examples of variables declared with the auto storage
class:

Example 1:

#include <stdio.h>

void exampleFunction() {

auto int num = 10;

printf("num: %d\n", num);

int main() {

exampleFunction();

return 0;

```

Output:

```

num: 10

```

In this example, the variable `num` is declared as an auto variable inside the `exampleFunction()` function. It is
created and initialized with the value 10 each time the function is called. The output will be `num: 10`.
Example 2:

#include <stdio.h>

int main() {

for (auto int i = 0; i < 5; i++) {

printf("%d ", i);

printf("\n");

return 0;

```

Output:

```

01234

```

In this example, an auto variable `i` is declared within the `for` loop. It is created and initialized with the value 0 at
the beginning of each iteration and is destroyed at the end of the iteration. The loop prints the values of `i` from 0
to 4.

Example 3:

#include <stdio.h>

int main() {

auto int x, y, sum;

x = 5;

y = 10;

sum = x + y;

printf("Sum: %d\n", sum);

return 0;
}

```

Output:

```

Sum: 15

```

In this example, three auto variables `x`, `y`, and `sum` are declared within the `main()` function. They are created
and initialized automatically. The values of `x` and `y` are assigned, and their sum is calculated and stored in the
`sum` variable. The output will be `Sum: 15`.

Note that explicitly using the `auto` keyword is optional since it is the default storage class in C.

2. `static` Storage Class:

This type of storage class gives an instruction to a compiler to keep the given local variable around during
the program’s lifetime- instead of creating it and then destroying it every time it comes into a scope and
goes out of it. Thus, when we make a local variable static, it allows the variable to maintain the values that
are available between various function calls.

We may also apply a static modifier to a global variable. When we do so, it will cause the scope of the
variable to be restricted to that file in which its declaration happened.

In a C programming language, when we use the static on a global variable, it will cause all the objects
present in a class to share a single copy of that given member.

For example,

#include <stdio.h>

/* declaration of function */

void func(void);

/* a global variable */

static int count = 10;

main() {
while(count–) {

func(); /* increment of function */

return 0;

void func( void ) {

/* definition of function */

static int x = 10; /* a local type of static variable */

x++;

printf(“x is %d and the count is %d\n”, x, count);

The compilation and execution of this code mentioned above will produce the result as follows:

When the above code is compiled and executed, it produces the following result −

x is 11 and the count is 9

x is 12 and the count is 8

x is 13 and the count is 7

x is 14 and the count is 6

x is 15 and the count is 5

Features of static variables:

 Those variables that we define as static specifiers are capable of holding their assigned value that
exists between various function calls.
 The static local variables are only visible to the block or the function in which we have defined
them.
 We can declare the very same static variable multiple times, but we can only assign it a single time.
 The initial value of a static integral variable, by default, is 0. Else, it is null.
 We use the static keyword in the case of a static variable.
 The visibility of any static global variable stays limited to that file in which we have declared it.

Example 1:
```c

#include <stdio.h>

void exampleFunction() {

static int counter = 0;

counter++;

printf("Counter: %d\n", counter);

int main() {

exampleFunction();

exampleFunction();

exampleFunction();

return 0;

```

Output:

```

Counter: 1

Counter: 2

Counter: 3

```

In this example, the `static` variable `counter` retains its value between function calls. The variable is initialized only
once and is updated each time the function is called.

Example 2:

```c

#include <stdio.h>

int increment() {

static int count = 0;


count++;

return count;

int main() {

printf("%d\n", increment());

printf("%d\n", increment());

printf("%d\n", increment());

return 0;

```

Output:

```

```

In this example, the `static` variable `count` is used to create a counter. It retains its value between function calls,
allowing the counter

to increment each time the `increment()` function is invoked.

Example 3:

```c

#include <stdio.h>

void outerFunction() {

static int x = 0;

void innerFunction() {

x++;
printf("x: %d\n", x);

innerFunction();

int main() {

outerFunction();

outerFunction();

outerFunction();

return 0;

```

Output:

```

x: 1

x: 2

x: 3

```

In this example, the `static` variable `x` is declared inside the `outerFunction()`. The `innerFunction()` can access and
modify the `x` variable across multiple invocations of `outerFunction()`.

3. `extern` Storage Class:

It is also known as the extern storage class, and we use it for giving a reference of any global variable
which is visible to all the files present in a program. When using the extern storage class, we cannot
initialize the variable. However, note that it points to the name of the variable at any storage location that
we have already defined (previously).

Whenever we have multiple numbers of files while we are trying to define any global variable or a function
(that will be used in various other files too), then we will use the extern in another file for providing the
reference of the defined function or variable. In simpler words, we use the entern for declaring a function
or a global variable in another file.

The most common use of the extern modifier is when we have two or more than two files that share a
similar global variable or function.

For example:

main.c (File 1) –

#include <stdio.h>

int count ;

variable void write_variable();

main() {

count = 38;

write_variable();

support.c (File 2) –

#include <stdio.h>

variable int count;

void write_variable(void) {

printf(“The variable for the program is %d\n”, count);

In this example, we have used the extern keyword for declaring the variable available in the second file.
On the other hand, its definition actually resides in the main.c (that is its first file). Now, the compilation of
both of these files will be as follows:

$gcc main.c support.c

This step will generate a program a.out that is executable in nature. When we perform the execution of this
program, we will get a result as follows:

The variable for the program is 38

The features of external variables:


We use the external storage class for conveying to the compiler that the variable that has been

defined as the extern has been declared using an external linkage that exists elsewhere in any
program.
 One can only perform the initialization of an external variable globally. In other words, one cannot
perform the initialization of an external variable within any given method or block.
 The variables that are declared as extern have no allocation of memory. It only has a declaration,
and it intends to specify that the given variable has been declared elsewhere in the available
program.
 An external integral type’s default initial value is going to be 0, or else it is null.
 We can initialize an external variable multiple times, but we can only initialize it a single time.
When we declare a variable as external, the compiler will start searching for that variable for initialization
somewhere in the available program. It might be static or extern. In case it isn’t, the compiler will
ultimately generate an error (a compile-time error).

Example 1 (file1.c):

#include <stdio.h>

extern int num; // Declaration of the variable defined in file2.c

int main() {

printf("num: %d\n", num);

return 0;

```

Example 1 (file2.c):

int num = 10; // Definition of the variable

int main() {

// Code in file2.c

return 0;

```
Output:

```

num: 10

```

In this example, the `extern` keyword is used to declare the variable `num` in `file1.c`, which is defined in `file2.c`.
The `extern` declaration allows `file1.c` to access the variable `num` defined in another source file.

Example 2 (file1.c):

#include <stdio.h>

extern int x; // Declaration of the variable defined in file2.c

void printX() {

printf("x: %d\n", x);

int main() {

printX();

return 0;

```

Example 2 (file2.c):

#include <stdio.h>

int x = 20; // Definition of the variable

void printX(); // Function prototype


int main() {

printX();

return 0;

void printX() {

printf("x: %d\n", x);

```

Output:

```

x: 20

x: 20

```

In this example, the variable `x` is declared as `extern` in `file1.c` and defined in `file2.c`. Both source files have a
function `printX()` that accesses and prints the value of `x`.

Example 3 (file1.c):

#include <stdio.h>

extern int x; // Declaration of the variable defined in file2.c

int main() {

printf("x: %d\n", x);

return 0;

```

Example 3 (file2.c):
#include <stdio.h>

int x = 30; // Definition of the variable

int main() {

printf("x: %d\n", x);

return 0;

```

Output:

```

x: 30

x: 30

```

In this example, both `file1.c` and `file2.c` contain a `main()` function, and both access the same external variable
`x`. The `extern` keyword allows sharing the variable between multiple files.

4. `register` Storage Class:

In the C programming language, storage classes are used to define the scope, visibility, and lifetime of variables. The
"register" storage class is the storage classes available in C. However, it is worth noting that the "register" storage
class has been deprecated in modern C standards and is typically ignored by compilers. Nevertheless, I can still
provide an explanation and examples for your reference.

The "register" storage class is used to suggest to the compiler that a particular variable should be stored in a CPU
register for faster access. It is important to note that the compiler is not obligated to honor this suggestion and may
choose to store the variable in memory instead.

Here are three examples of using the "register" storage class:


Example 1:

#include <stdio.h>

int main() {

register int i; // Declare a register variable

for (i = 1; i <= 10; i++) {

printf("%d ", i);

return 0;

```

In this example, the variable `i` is declared as a register variable. However, since the "register" storage class is
ignored by modern compilers, the variable `i` will likely be stored in memory like any other variable. This code
simply prints the numbers from 1 to 10.

Example 2:

#include <stdio.h>

void swap(register int* a, register int* b) {

register int temp; // Declare register variables

temp = *a;

*a = *b;

*b = temp;

int main() {

int x = 10, y = 20;


swap(&x, &y);

printf("x: %d, y: %d\n", x, y);

return 0;

```

In this example, the `swap` function takes two pointers to integers and swaps their values using register variables
`temp`. Again, since the "register" storage class is typically ignored, the variables `temp`, `x`, and `y` will likely be
stored in memory. The output will be `x: 20, y: 10`, indicating the successful swap of values.

Example 3:

#include <stdio.h>

int factorial(register int n) {

if (n == 0 || n == 1) {

return 1;

} else {

return n * factorial(n - 1);

int main() {

int num = 5;

int result = factorial(num);

printf("Factorial of %d is %d\n", num, result);

return 0;

}
```

In this example, the `factorial` function calculates the factorial of a number using recursion. The function argument
`n` is declared as a register variable. However, as mentioned before, the compiler may ignore the "register" storage
class, and the variable `n` will likely be stored in memory. The output will be `Factorial of 5 is 120`, indicating the
factorial calculation.

Remember, while using the "register" storage class is deprecated, modern compilers are capable of optimizing code
without explicitly specifying it. Therefore, it is unnecessary to rely on the "register" storage class for performance
optimization in C programs.

You might also like