Static Const Member Variable in C++

In this article, we will be learning about the static const member variable in C++ which is a combination of const which is a type qualifier and static which is a storage specifier. We will learn about both of them in this article using the C++ language.

Static

Any variable which has a static word behind it will never be destroyed while the program is running, whereas the other variables with normal variable declaration get destroyed after the function is over. So basically it tells us about the lifetime of the variable.

Const

Any variable with const before it cannot be changed further in the program. The variable has a constant value throughout the program which is the same as at the time of its declaration. It is a type qualifier.

Static Const in C++

So when we combine static and const to a variable, then that variable will not be destroyed till the program is over and its value cannot be changed throughout the program. Let us see it with the help of the code below in C++.

#include<bits/stdc++.h>
using namespace std;

// value 5 in a will be stored
// till the program ends
int fun(int x)
{
    static const int a=5;

    // const value will not allow
    // to change value
    const int b=5;
    x+=a;

//    a++;   this line produces error 
//            as a was static const so 
//              can't be changed
    return x;
}
int main()
{
    int x=15;
    cout<<fun(x)<<endl;
}

Output:

20

Thank you for reading!!
I hope it helps!!

Leave a Reply

Your email address will not be published. Required fields are marked *