Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024

Storage class

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Storage classes are used to describe the functions of a variable/function. Those features essentially include the scope, visibility, and lifestyles-time, which help us trace the lifestyles of a selected variable during the run-time of a program.

Also see, Literals in C, Fibonacci Series in C++

Types of Storage class

  • Automatic
  • Register
  • Static
  • External
  • Mutable

Automatic

It is a default storage class for all nearby variables. They are called local variables that are declared interior a function or a block. Auto variables can only be called within the function or a block in which they had been declared, i.e., cannot be accessed outside from that function or block. We can also access them inside nested blocks and the parent block where the declaration of the car variable is. Pointer variables are used to access auto variables outdoor their scope. We point to the same region in the memory where variables are stored. Its lifespan depends on the function's lifetime(same as the function's lifetime), i.e., when a function's execution is complete, the variable is destroyed. Using the default, they are given a rubbish fee whenever declared.

Example

#include <iostream>
using namespace std;
void autoStorageClass()
{
  cout << "Demonstration of auto storage class\n";
  // Declare an auto variable
  // We do not need data-type declaratiion
  auto a = 50;
  auto b = 5.2;
  auto c = "AutoStorageClass";
  auto d = 'A';
  // Displaying the auto variables
  cout << a << " \n";
  cout << b << " \n";
  cout << c << " \n";
  cout << d << " \n";
}
int main()
{
  // Demonstrating auto Storage Class
  autoStorageClass();
  return 0;
}

Output

Demonstration of auto storage class
50 
5.2 
AutoStorageClass 
A 

 

You can try and compile with the help of online c++ compiler.

Register

We declare register variables using the register storage class. A sign-in variable functions further to an auto variable. The most effective exception is that the compiler tries to save these variables in the microprocessor's sign-up if one is available.

If no accessible registers are available, they are entirely saved in memory. Operations on register variables are much faster than other variables saved in memory during run-time.

A few variables that need to be accessed often in a program are usually declared in the register storage class. This helps increase the program's execution speed. A register variable's address cannot be found via pointers. The variable's most apparent size is equal to the register's largest size. We cannot use the '&' operator because there is no memory location for it.

Example

#include <iostream>
using namespace std;
void registerStorageClass()
{
	cout << "Demonstration of register storage class\n";
	// declaration of a register variable
	register char c = 'G';
	//Lets dispkay the register variable
	cout << "Value of 'c' which is"
	<< " declared as register: " << c;
}
int main()
{
	// Demonstrating the Storage Class
	registerStorageClass();
	return 0;
}

Output

Demonstration of register storage class
Value of, which is declared as register: G

Static

Static variables are declared using the storage class. Static variables maintain their cost even if they may be out of doors their scope. They're initialized as soon as and exist till the program is terminated. The memory for the static variable is simplest allotted once, and no extra memory is allocated as it is not re-declared.

We can access global static variables everywhere in the code. The compiler assigns the value zero to them by default. In C++, whilst we use static on a class data member, all objects share only one copy of that member in that class.

Example

#include <iostream>
using namespace std;
// Function that contains static variables
// memory is retained during execution
int staticFun()
{
	cout << "Static variables: ";
	static int count = 0;
	count++;
	return count;
}
// Function that contains non-static variables
// Destroying memory
int nonStaticFun()
{
	cout << "Non-Static variables: ";
	int count = 0;
	count++;
	return count;
}
int main()
{
	// Printing the static variables parts
	cout << staticFun() << "\n";
	cout << staticFun() << "\n";
	// Printing the non-static variables parts
	cout << nonStaticFun() << "\n";
	cout << nonStaticFun() << "\n";
	return 0;
}

Output

static variables: 1
static variables: 2
Non-Static variables: 1
Non-Static variables: 1

External

We need this storage class whilst we want the variables to be shared throughout several files. Outside variables have a global scope and may be seen outside of the file where they were declared. The whole program can see it, and it's far utilized whilst the same variable or characteristic is shared via or more documents.

The lifetime of the external variable is the same as the lifetime of the program in which they were declared. A regular global variable will also be rendered external by using the 'extern' keyword before its statement or description in any function or block.

The variable can not be initialized while you use 'extern' because it points the variable name to a previously decided storage address.

Example

#include <iostream>
using namespace std;
// Declaring the variable which is to
// be made extern an initial value can
// also be initialized to m
int m;
void externStorageClass()
{
	// We tell compiler that variable
	// m is an extern variable. It's been defined somewhere else (above the main function)
	extern int m;
	// printing the extern variables
	cout << "Initialized value of 'm'which is "
	<< "declared as extern: " << m << "\n";
	// value of 'm' modified
	m = 15;
	// printing the modified values of
	// extern variables
	cout
	<< "Modified value of 'm'"
	<< " declared as extern: "
	<< m;
}
int main()
{
	// Demonstration of extern Storage Class
	externStorageClass();
	return 0;
}

Output

Initialized value of 'm' which is declared as extern: 0
Modified value of 'm' declared as extern: 15

Mutable

Only class objects have a mutable specifier. This enables a member of an object to override a const member function. This is, a const member function can exchange a mutable member.

Even if you don't need the function to update different contributors of the class/struct, you would possibly want to exchange one or greater information participants. The usage of the const function executes this. The mutable keyword makes this task easy to finish.

Example

#include <iostream>
using std::cout;
class Test 
{
  public:
  int m;
  // Defining mutable variable n
  // which can be modified
  mutable int n;
  Test()
  {
    m = 5;
    n = 20;
  }
};
int main()
{
  // Our t1 is set to constant
  const Test t1;
  // We are trying to change the value
  t1.n = 50;
  cout << t1.n;
  // Not commenting below the lines
  // will throw errors
  // t1.m = 8;
  // cout << t1.m;
  return 0;
}

Output

50
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

1. What is the storage class for variable A in the below code?

int main()
{
   int A;
   A = 10;
   printf("%d", A);
   return 0;
}

Ans: Here are four types of storage classes in C, and those are auto, register, extern and static. Whenever a local variable is declared, i.e., variable A, it is counted in the auto storage class, and each storage class has some default value. In the case of auto, its default values are garbage.

 

2.What is the output ?

int main()
{
	extern int i;
	i = 20;
	printf("%d", sizeof(i));
	return 0;
}

Ans: extern int i; tell the compiler that int i is declared in another file. In this code, we haven't included any other header file, so it will cause a compilation error.
 

3. The following statement is a declaration or definition ?

extern int i;

Ans: Declaration

Key Takeaways

In this article, we mentioned the different methods that we can use as storage class's in C++ programs and what they are and their roles. With that, you must create programs that use storage classes to express the attributes of variables and methods. Are you planning to ace the interviews of reputed product-based companies like Amazon, Google, Microsoft, and more? Attempt our Online Mock Test Series on Coding Ninjas Studio now!

Topics covered
1.
Introduction
2.
Types of Storage class
2.1.
Automatic
2.1.1.
Example
2.2.
Register
2.2.1.
Example
2.3.
Static
2.3.1.
Example
2.4.
External
2.4.1.
Example
2.5.
Mutable
2.5.1.
Example
3.
Frequently Asked Questions
4.
Key Takeaways