C Storage Class Specifiers - auto, register, static and extern

    0 Votes

We know that, a specific number of bytes of space is required to store a value of a variable as needed by the type of variable. For example, 'char' requires 1 byte, 'int' requires 2/4 byte and so on. This space can be allocated from the memory of the system or from processor registers. Register access is always faster than memory access. What if we can specify to the compiler about where to store the variable? Also, how long to keep the value of variable in memory, it's initial value etc? Storage class specifiers are used for that purpose. Using storage class specifiers we can specify

  1. Where to store the value of variable: registers of memory
  2. Specify the scope of the variable
  3. Specify life time of variable

Storage class specifiers available in C programming language include 'auto', 'register', 'static' and 'extern'.

'Auto' Storage Class Specifier

A variable declared as 'auto' qualifier implies that the variable exists/accessible only with in the code block they are declared. For all the code blocks outside the declared code block, it's as if the variable doesn't exist. If some code outside of the code block tries to access an 'auto' variable, it will cause compilation error. By default, all variables are of auto storage class.

Let's take a look at an example of 'auto' storage class.

#include <stdio.h>
int main( )
{ //Code block 1

    auto int a = 1;
    { //Code block 2

        auto int a = 2;
        { //Code Block 3

            auto int a = 3;
            printf ( "\n Value of 'a' in Code Block 3: %d", a);
        }
        printf ( "\n Value of 'a' in Code Block 2: %d", a);
    }
    printf ( "\n Value of 'a' in Code Block 1: %d", a);
}

Output:
 Value of 'a' in Code Block 3: 3
 Value of 'a' in Code Block 2: 2
 Value of 'a' in Code Block 1: 1

From the above example, you can see that value of variable 'a' is different in each code block because they are declared as 'auto' and has scope only with in the declared block. The behaviour would be same even if you remove the 'auto' keyword from the variable declaration, because by default all variables are of type 'auto'.

Life of 'auto' variable is within the declared code block, they will cease to exist after the execution of corresponding code block and the initial value of variable would be garbage. So they need to be initialized with proper value before usage.

'Register' Storage Class Specifier

'register' storage class is same as 'auto' except that 'register' variables are stored in CPU registers compared to 'auto' where 'auto' variables are stored in RAM. The scope of 'register' class variable is same as 'auto' class variable, i.e. they can't be accessed outside the code block they are declared. 'register' variables will also be initialized with garbage value.

Example of register storage class is given below

#include <stdio.h>
int main( )
{ //Code block 1

    auto int a = 1;
    { //Code block 2

        auto int a = 2;
        { //Code Block 3

            auto int a = 3;
            printf ( "\n Value of 'a' in Code Block 3: %d", a);
        }
        printf ( "\n Value of 'a' in Code Block 2: %d", a);
    }
    printf ( "\n Value of 'a' in Code Block 1: %d", a);
}

Output:
 Value of 'a' in Code Block 3: 3
 Value of 'a' in Code Block 2: 2
 Value of 'a' in Code Block 1: 1

Since CPU register access is faster than memory access, declaring frequently accessed variables as 'register' will improve the performance of program. But one important thing to note about 'register' variable is, it's not guaranteed that those variables will be stored in CPU registers because number of registers is very limited for a CPU. So, if all the registers are allocated for other variables or purposes, then a variable will get stored in RAM even if it's declared as 'register' type.

Also, you cannot request address of a register variable using address operator (&). This will result in compilation error because 'register' variables might not be stored on RAM.

'Static' Storage Class Specifier

  • Value of a 'Static' variable will be maintained across the function invocations. If a variable is declared using 'Static' qualifier at the top of the source file, then the scope of that variable is within the entire file. Files outside the declared file can't access the declared static variable. 
  • 'Static' variables declared within a function or a block, also known as local static variables, have the scope that, they are visible only within the block or function like local variables. The values assigned by the functions into static local variables during the first call of the function will persist/available until the function is invoked again.
  • 'Static' variables are by default initialized with value 0.


Let's see the effect of declaring a local and global variable with 'Static' keyword.

#include <stdio.h>
static int global_static_variable = 1;

static void static_variable_test() {
    static int local_static_variable;
    printf("local_static_variable:%d\t", local_static_variable);
    local_static_variable++;
    printf("global_static_variable:%d\n", global_static_variable);
    global_static_variable++;
}
 
int main()
{
    static_variable_test();
    static_variable_test();
}

Output:
 local_static_variable:0    global_static_variable:1
 local_static_variable:1    global_static_variable:2

Few points to note here are

  1. 'Static' variable got initialized with value 0 by default. (We didn't initialize the variable 'local_static_variable' with a value, but it got initialized with 0 automatically)
  2. Value of the the local variable 'local_static_variable' is retained across invocations of function 'static_variable_test()'

Also Read - Top C Interview Questions and Answers for Freshers & Advanced C Interview Questions and Answers

'Static' and Global functions/variables

In C programming language, functions are global by default. That means, by default function declared in a file can be accessed from code with in another file. But when you apply static keyword to a functions, it makes the function accessible only from that file. So if you want to restrict access to a function from code in other files, you can declare the function as static.

In the example given above, the function 'static_variable_test' will be visible only with in the file it's declared. Also, if you declare a global variable as static, code in other files cannot access the variable. In simple words, declaring a global function or variable as static gives it internal linkage.

'Extern' Storage Class Specifier

'extern' storage class defines a global variable visible /accessible to all files when linking. That means, 'extern' keyword informs the compiler that the variables declared using the keyword is already defined somewhere else in the program. Since the extern is defined at some other place in the program, trying to initialize an extern variable as part of declaration creates compilation error, because initialization makes the declaration statement a definition and it's in turn redefining a variable defined already. If the 'extern' variable is not defined else where in program, then you can initialize it as part of declaration (But compiler might give a warning message).

Let's take a look an example using extern storage class specifier

#include <stdio.h>
// This is only a declaration
extern int extern_variable;
int main()
{
  printf("extern_variable: %d", extern_variable);
  return 0;
}

// Actual definition occurs here
int extern_variable = 20;

Output:
 extern_variable: 20

In the above program, 'extern_variable' is defined at the end of file, but since it's declared using extern keyword, compiler can properly link it.

Also Read - Top Embedded C Interview Questions and Answers & C++ Interview Questions and Answers

'Extern' and Functions

You can use extern keyword along with function declaration as well, but that's a redundant operation since functions have external linkage by default. ie; They can be accessed globally from other places.

'Typedef' Qualifier

'typedef' is not a storage class specifier, but it allows us to give an alias (new name) to existing data types (built-in or user defined datatypes). Sytax of 'typedef' is as given below,

typedef data_type alias; 

Let's consider the following example

typedef int number;

Here, we've given an alias to data type 'int' which is 'number'. So now we can use 'number' as a type in variable declaration and definition to hold an integer values. By creating an alias, we can use it as given below

number first, second;

It means 'first' and 'second' are of the 'number' data type which in turn is an integer. So, 'first' and 'second' are also integers.

Summary of Storage Class Specifiers

Table given below summarizes the storage location, initial default value, scope and life time of different storage class specifiers

Storage ClassSpace Allocated inDefault Initial ValueScopeLife
auto Memory Garbage Local Scope Alive within the declared code block
register CPU Register Garbage Local Scope Alive within the declared code block
static Memory 0 Local Scope Value retained between invocations
extern Memory 0 Global Scope Alive till program exit

Related Articles

C Overview and Basic Syntax
Data Types in C Language
C Qualifiers - Constant and Volatile type Qualifier
C Type Casting with examples - float to int / int to char / int to long
C Constants and Literals
C Operators - Arithmetic, Assignment, Relational and Logical
C Operators - Bitwise Operators and Conditional Operators
C Operator Precedence and Associativity Table with Examples
C Input and Output Statements
C Format Specifiers for printf and scanf
C Decision Making Control Structures - 'if', 'if - else', nested 'if', 'switch'
Loops in C - for, while and do...while Loops
C 'break', 'continue' and 'goto' Statements to Control Program Flow
C Preprocessor Directives and Macros
C Functions Tutorial with Examples
C Arrays - Dynamic, 2d and Multidimensional with Examples
C Strings - Internal Working and Functions with example
C Pointers basics explained with examples
Structures in C Programming with Example
Unions in c programming with example

Popular Videos

How to speak to people

How to speak so that people want to listen.

Got a tip or Question?
Let us know