English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C ++Static keyword in

When using the static keyword, you cannot modify the variable or data member or function again. It is allocated throughout the life cycle of the program. Static functions can be called directly using the class name.

Static variables are initialized only once. The compiler retains the variable until the end of the program. Static variables can be defined inside or outside the function. They are block-local. The default value of static variables is zero. Static variables are valid before the program execution.

This is C ++Syntax of the static keyword in the language,

static datatype variable_name = value;      // Static variable
static return_type function_name {             // Static functions
   ...
}

Here,

datatype-Data type of the variable, such as int, char, float, etc.

variable_name-This is the variable name given by the user.

Value-Any value to initialize the variable. By default, it is zero.

return_type-Data type of the function's return value.

function_name-The function'sAny name.

This is C ++Static variable example in the language,

Example

#include <bits/stdc++.h>
using namespace std;
class Base {
   public : static int val;
   static int func(int a) {
      cout << "\nStatic member function called";
      cout << "\nThe value of a: " << a;
   }
};
int Base::val=28;
int main() {
   Base b;
   Base::func(8);
   cout << "\nThe static variable value: " << b.val;
   return 0;
}

Output result

Static member function called
The value of a 8
The value of the static variable 28

In the above program, a static variable is declared in the Base class and a static function is defined as follows-

public : static int val;
static int func(int a) {
   cout << "\nStatic member function called";
   cout << "\nThe value of a: " << a;
}

After and before the classmain()The initialization of the static variable is as follows:

int Base::val=28;

In this functionmain()It creates an object of the base class and calls the static variable. The static function is also called without using an object of the Base class, as shown below:

Base b;
Base::func(8);
cout << "\nThe static variable value: " << b.val;