当前位置:网站首页>Variable category (automatic, static, register, external)

Variable category (automatic, static, register, external)

2022-07-05 04:34:00 On the bald Road

1.auto Automatic variable

auto int a = 0; Will report a mistake !!!

An error message appears :"auto” Cannot be combined with any other type specifier , Because the new version C++ Definition auto Cannot be combined with any type .

!!! If a variable is declared without keywords , That's automatic .

2,static Static variables .

Hopefully, after the function call ends , Among them, the variable value will not disappear, and you can use static variables . The next time you call a function , This variable calls the value at the end of the last function call .

for example

#include<iostream>
using namespace std;
int fun(int);
int main() {
	int n = 5;
	for (int i = 1; i <= n; i++) {
		cout << i << "!=" << fun(i) << endl;
	}
	return 0;
}
int fun(int i) {
	/*auto int a = 0;   Will report a mistake !!!*/

	static int n = 1;
	n = i * n;
	return n;


}

The running result is :

1!=1
2!=2
3!=6
4!=24
5!=120

Some properties of static variables : Assign initial value to , The default is 0; and auto The default is random , And an error will be reported .

register Register variables

Some variables used many times , In order to improve the efficiency of execution ,c++ It is allowed to store the value of a local variable in CPU In the register of , No need to call from memory .

extern Declared external variables

Its scope starts from the definition of variables , To the end of this procedure , In this scope , Global variables can be referenced by various functions in this document .!!!! At compile time, global variables will be allocated in static storage .

matters needing attention : A program that contains multiple files , If you define the same variable in different files , Errors will be reported when linking , So put a variable extern To declare as an external variable .

--------------------------------------------------------------------------------------------------------------------------------

Add :

1. Automatic variable Register variables For dynamic storage ; Static local variables , Static external variables , External variables are stored statically .

2. Internal function for example :static int func(int a) Limit functions to this document , If there are internal functions with the same name in different files , Mutual interference . Referred to as localization ;

External function example :extern  int func(int a) Expressed as an external function that can be called by other files .

原网站

版权声明
本文为[On the bald Road]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140636192877.html