Code Point Blog

Iam presenting here ,all type of knowledge if you want to interest knowing about any topic then click below thumbnail view button and knowing.

All Chapter Back to Home Page

Storage class in language

In C programming, storage classes are specifiers used to control the scope, visibility, and lifetime of variables and functions within a program. C provides four primary storage classes:

1.auto : The 'auto' storage class is the default for local variables declared within a block (inside a function or a compound statement). It is rarely used explicitly because local variables are automatically considered `auto` by default. The 'auto' keyword is optional and is often omitted in practice.

    
     #include <stdio.h>
     void exampleFunction() {
        auto int x = 10; // 'auto' is optional (same as 'int x = 10;') 
        } 
                                
     
     

2.register :The `register` storage class is used to suggest to the compiler that a variable should be stored in a CPU register for faster access. However, the compiler is not obligated to comply with this suggestion, and the use of `register` is mostly ignored in modern compilers.

    
     #include <stdio.h>
     void exampleFunction() { 
        register int count = 0; // Suggests using a register for 'count' 
        } 
                                    
    
    

3.tatic The `static` storage class is used to create variables with a lifetime throughout the program's execution, rather than just within a specific block. Static variables are initialized only once, and their value persists across function calls.

    
        #include <stdio.h>
        void exampleFunction() { 
            static int counter = 0; // Initialized only once 
            counter++; 
            printf("Counter: %d\n", counter); 
            } 
                                
    
    

4.extern : The `extern` storage class is used to declare a variable or function that is defined in another file. It is used to provide the compiler with information about an external symbol's existence without allocating memory for it.

(In one file (file1.c)) extern int sharedVariable;
(In another file (file2.c)) int sharedVariable = 10;

Understanding storage classes is crucial for managing variable scope and lifetime in C programs. Different storage classes have different lifetimes, scopes, and behavior, impacting how variables and functions are used in a C program.