C++ Tutorial – Storage Specifiers


This C++ Tutorial concentrates on some of the storage class specifiers in C++. The storage class specifiers are used to change the way of creating the memory storage for the variables.

C++ tutorial – auto:

This auto specifier tells the compiler that the variable declared will go out of scope once the program exits from the current block. The program block can be a function, a class or a structure.

This is the most widely used and non-used storage class specifier in C++. Because, all the variables declared in C++ are of the type auto by default. So no one need to worry about specifying this one. The declarations,

auto int var1; // declared with auto specifier for the c++ tutorial
int var1; //declared without the storage class specifier

Both the above declarations will produce the same result.

C++ tutorial – static:

This static specifier when used will preserve the value for a particular variable upon re-entry into the same function. For example

//C++ Tutorial - Example code for demonstrating static variable
void static_function_example()
{
static int x = 0; //variable for C++ tutorial example
x++;
cout << x <<endl;
}

If this function is called 10 times, the output will be 1,2,3,4..etc., The value of the variable x is preserved through function calls.

If this static variable is declared as a member of a class, then it will preserve the value for all the objects of the class.i.e, one copy of this data variable will be shared by all objects of the class.

C++ tutorial – extern:

This extern keyword is used to specify that the variable is declared in a different file. This is mostly used to declare variables of global scope in C++ projects. When the keyword extern is used, the compiler will not allocate memory for the variable. Programmers in C++ would have very frequently faced linker errors because of wrong external linking.

C++ tutorial – register storage specifier:

This register keyword tells the C++ compiler to allocate some storage in the registers. Any operations using the register is bound to be the fastest. But a mere specification of register keyword won’t get the variable a place in the register. If the compiler finds no space in the register, it’ll use the cache memory also.

C++ tutorial – mutable storage specifier:

This mutable keyword if specified before a variable, will allow the const member function to modify the const data.