The document discusses different storage classes in C++ including automatic, external, static, register, and mutable. It provides the syntax and examples of each:
- Automatic variables are declared with auto and have function block scope and lifetime.
- External variables use extern and have whole program global visibility.
- Static variables are declared with static and have whole program lifetime but local visibility.
- Register variables are intended for fast access and declared with register but storage is implementation-defined.
- Mutable variables allow changing class member values in const member functions and are declared with mutable.
4. Storage Class Keyword Lifetime Visibilty
Automatic auto Function Block Local
External extern Whole Program Global
Static static Whole Program Local
Register register Function Block Local
Mutable Mutable Class Local
5. Automatic Storage Class
Syntax of Automatic Storage :
datatype var_name1 [= value];
Or
auto datatype var_name1 [= value];
Example of Automatic Storage Class :
auto int x;
float y = 5.67;
7. Example of External Storage Class
File: sub.cpp
int test=100; // assigning value to test
void multiply(int n)
{
test=test*n;
}
File: main.cpp
#include<iostream>
#include "sub.cpp" // includes the content of sub.cpp
using namespace std;
extern int test; // declaring test
int main()
{
cout<<test<<endl;
multiply(5);
cout<<test<<endl;
return 0;
}
Output
100
500
8. Static Storage Class
Syntax of Static Storage Class
static datatype var_name1 [= value];
For example
static int x = 101;
static float sum;
9. Register Storage Class
Syntax of Register Storage Class
register datatype var_name1 [= value];
For example
register int id;
register char a;
10. Example : C++ program to create automatic,
static and register variables.
#include<iostream>
using namespace std;
int g; //global variable, initially holds 0
void test_function()
{
static int s; //static variable, initially
holds 0
register int r; //register variable
r=5;
s=s+r*2;
cout<<"Inside test_function"<<endl;
cout<<"g = "<<g<<endl;
cout<<"s = "<<s<<endl;
cout<<"r = "<<r<<endl;
}
int main()
{
int a; //automatic variable
g=25;
a=17;
test_function();
cout<<"Inside main"<<endl;
cout<<"a = "<<a<<endl;
cout<<"g = "<<g<<endl;
test_function();
return 0;
}