C++ c和c++上下文中静态、自动、全局和局部变量的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13415321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between static, auto, global and local variable in the context of c and c++
提问by user1779646
I've a bit confusion about static
, auto
, global
and local
variables.
我已经约了一些混乱static
,auto
,global
和local
变量。
Somewhere I read that a static
variable can only be accessed within the function, but they still exist (remain in the memory) after the function returns.
在某处我读到一个static
变量只能在函数内访问,但在函数返回后它们仍然存在(保留在内存中)。
However, I also know that a local
variable also does the same, so what is the difference?
但是,我也知道一个local
变量也有同样的作用,那么有什么区别呢?
回答by Mike Seymour
There are two separate concepts here:
这里有两个独立的概念:
- scope, which determines where a name can be accessed, and
- storage duration, which determines when a variable is created and destroyed.
- scope,它确定可以访问名称的位置,以及
- storage duration,它决定了何时创建和销毁变量。
Localvariables (pedantically, variables with block scope) are only accessible within the block of code in which they are declared:
局部变量(迂腐地,具有块作用域的变量)只能在声明它们的代码块内访问:
void f() {
int i;
i = 1; // OK: in scope
}
void g() {
i = 2; // Error: not in scope
}
Globalvariables (pedantically, variables with file scope(in C) or namespace scope(in C++)) are accessible at any point after their declaration:
全局变量(迂腐地,具有文件范围(在 C 中)或命名空间范围(在 C++ 中)的变量)在声明后的任何时候都可以访问:
int i;
void f() {
i = 1; // OK: in scope
}
void g() {
i = 2; // OK: still in scope
}
(In C++, the situation is more complicated since namespaces can be closed and reopened, and scopes other than the current one can be accessed, and names can also have class scope. But that's getting very off-topic.)
(在 C++ 中,情况更加复杂,因为命名空间可以关闭和重新打开,并且可以访问当前范围以外的范围,并且名称也可以具有类范围。但这变得非常离题。)
Automaticvariables (pedantically, variables with automatic storage duration) are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered.
自动变量(迂腐,具有自动存储期的变量)是局部变量,其生命周期在执行离开其作用域时结束,并在重新进入作用域时重新创建。
for (int i = 0; i < 5; ++i) {
int n = 0;
printf("%d ", ++n); // prints 1 1 1 1 1 - the previous value is lost
}
Staticvariables (pedantically, variables with static storage duration) have a lifetime that lasts until the end of the program. If they are local variables, then their value persists when execution leaves their scope.
静态变量(迂腐地,具有静态存储期的变量)的生命周期一直持续到程序结束。如果它们是局部变量,那么当执行离开它们的作用域时它们的值仍然存在。
for (int i = 0; i < 5; ++i) {
static int n = 0;
printf("%d ", ++n); // prints 1 2 3 4 5 - the value persists
}
Note that the static
keyword has various meanings apart from static storage duration. On a global variable or function, it gives it internal linkageso that it's not accessible from other translation units; on a C++ class member, it means there's one instance per class rather than one per object. Also, in C++ the auto
keyword no longer means automatic storage duration; it now means automatic type, deduced from the variable's initialiser.
请注意,static
除了静态存储持续时间之外,关键字还有多种含义。在全局变量或函数上,它赋予它内部链接,以便其他翻译单元无法访问它;在 C++ 类成员上,这意味着每个类有一个实例,而不是每个对象有一个。此外,在 C++ 中,auto
关键字不再表示自动存储持续时间;它现在意味着从变量的初始值设定项推导出的自动类型。
回答by Freak
First of all i say that you should google this as it is defined in detail in many places
Local
These variables only exist inside the specific function that creates them. They are unknown to other functions and to the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the function that created them is completed. They are recreated each time a function is executed or called.
Global
These variables can be accessed (ie known) by any function comprising the program. They are implemented by associating memory locations with variable names. They do not get recreated if the function is recalled.
首先我说你应该google this,因为它在很多地方都有详细定义
Local
这些变量只存在于创建它们的特定函数中。它们对其他函数和主程序是未知的。因此,它们通常使用堆栈来实现。一旦创建它们的函数完成,局部变量就不再存在。每次执行或调用函数时都会重新创建它们。
全局
这些变量可以被包含程序的任何函数访问(即已知)。它们是通过将内存位置与变量名称相关联来实现的。如果调用该函数,则不会重新创建它们。
/* Demonstrating Global variables */
#include <stdio.h>
int add_numbers( void ); /* ANSI function prototype */
/* These are global variables and can be accessed by functions from this point on */
int value1, value2, value3;
int add_numbers( void )
{
auto int result;
result = value1 + value2 + value3;
return result;
}
main()
{
auto int result;
value1 = 10;
value2 = 20;
value3 = 30;
result = add_numbers();
printf("The sum of %d + %d + %d is %d\n",
value1, value2, value3, final_result);
}
Sample Program Output
The sum of 10 + 20 + 30 is 60
The scope of global variables can be restricted by carefully placing the declaration. They are visible from the declaration until the end of the current source file.
可以通过小心放置声明来限制全局变量的范围。它们从声明到当前源文件的结尾都是可见的。
#include <stdio.h>
void no_access( void ); /* ANSI function prototype */
void all_access( void );
static int n2; /* n2 is known from this point onwards */
void no_access( void )
{
n1 = 10; /* illegal, n1 not yet known */
n2 = 5; /* valid */
}
static int n1; /* n1 is known from this point onwards */
void all_access( void )
{
n1 = 10; /* valid */
n2 = 3; /* valid */
}
Static:
Static object is an object that persists from the time it's constructed until the end of the program. So, stack and heap objects are excluded. But global objects, objects at namespace scope, objects declared static inside classes/functions, and objects declared at file scope are included in static objects. Static objects are destroyed when the program stops running.
I suggest you to see this tutorial list
AUTO:
C, C++
静态:
静态对象是一个从它被构造到程序结束一直存在的对象。因此,堆栈和堆对象被排除在外。但是全局对象、命名空间范围内的对象、在类/函数中声明为静态的对象以及在文件范围内声明的对象都包含在静态对象中。当程序停止运行时,静态对象会被销毁。
我建议你看这个教程列表
AUTO:
C, C++
(Called automatic variables.)
(称为自动变量。)
All variables declared within a block of code are automatic by default, but this can be made explicit with the auto keyword.[note 1] An uninitialized automatic variable has an undefined value until it is assigned a valid value of its type.[1]
默认情况下,在代码块中声明的所有变量都是自动的,但这可以使用 auto 关键字明确。[注 1] 未初始化的自动变量具有未定义的值,直到它被分配了其类型的有效值。[1]
Using the storage class register instead of auto is a hint to the compiler to cache the variable in a processor register. Other than not allowing the referencing operator (&) to be used on the variable or any of its subcomponents, the compiler is free to ignore the hint.
使用存储类寄存器而不是 auto 提示编译器将变量缓存在处理器寄存器中。除了不允许在变量或其任何子组件上使用引用运算符 (&) 之外,编译器可以随意忽略提示。
In C++, the constructor of automatic variables is called when the execution reaches the place of declaration. The destructor is called when it reaches the end of the given program block (program blocks are surrounded by curly brackets). This feature is often used to manage resource allocation and deallocation, like opening and then automatically closing files or freeing up memory.SEE WIKIPEDIA
在 C++ 中,自动变量的构造函数在执行到声明的地方时被调用。当它到达给定程序块的末尾时调用析构函数(程序块被大括号包围)。此功能通常用于管理资源分配和释放,例如打开然后自动关闭文件或释放内存。见维基百科
回答by user1746468
Difference is static variables are those variables: which allows a value to be retained from one call of the function to another. But in case of local variables the scope is till the block/ function lifetime.
不同之处在于静态变量是那些变量:它允许从一个函数调用到另一个函数调用保留一个值。但是在局部变量的情况下,范围是直到块/函数生命周期。
For Example:
例如:
#include <stdio.h>
void func() {
static int x = 0; // x is initialized only once across three calls of func()
printf("%d\n", x); // outputs the value of x
x = x + 1;
}
int main(int argc, char * const argv[]) {
func(); // prints 0
func(); // prints 1
func(); // prints 2
return 0;
}
回答by Yuushi
static
is a heavily overloaded word in C and C++. static
variables in the context of a function are variables that hold their values between calls. They exist for the duration of the program.
static
在 C 和 C++ 中是一个重载的词。static
函数上下文中的变量是在调用之间保存其值的变量。它们在计划期间存在。
local variables persist only for the lifetime of a function or whatever their enclosing scope is. For example:
局部变量仅在函数的生命周期内或它们的封闭范围内持续存在。例如:
void foo()
{
int i, j, k;
//initialize, do stuff
} //i, j, k fall out of scope, no longer exist
Sometimes this scoping is used on purpose with { }
blocks:
有时这种作用域是故意与{ }
块一起使用的:
{
int i, j, k;
//...
} //i, j, k now out of scope
global variables exist for the duration of the program.
全局变量在程序运行期间存在。
auto
is now different in C and C++. auto
in C was a (superfluous) way of specifying a local variable. In C++11, auto
is now used to automatically derive the type of a value/expression.
auto
现在在 C 和 C++ 中有所不同。auto
在 C 中是一种指定局部变量的(多余的)方式。在 C++11 中,auto
现在用于自动派生值/表达式的类型。
回答by iammilind
Local variables are non existentin the memory after the function termination.
However static
variables remain allocatedin the memory throughout the life of the program irrespective of whatever function.
函数终止后,局部变量在内存中不存在。
然而,无论函数如何,static
变量在程序的整个生命周期中都保持在内存中的分配状态。
Additionally from your question, static
variables can be declared locally in class
or function scope and globally in namespace
or file scope. They are allocated the memory from beginning to end, it's just the initialization which happens sooner or later.
此外,根据您的问题,static
可以在class
或 函数范围内局部声明变量,并在namespace
或文件范围内全局声明变量。他们从头到尾分配内存,这只是迟早会发生的初始化。
回答by user3472599
When a variable is declared static inside a class then it becomes a shared variable for all objects of that class which means that the variable is longer specific to any object. For example: -
当一个变量在类中声明为静态时,它就成为该类所有对象的共享变量,这意味着该变量不再特定于任何对象。例如: -
#include<iostream.h>
#include<conio.h>
class test
{
void fun()
{
static int a=0;
a++;
cout<<"Value of a = "<<a<<"\n";
}
};
void main()
{
clrscr();
test obj1;
test obj2;
test obj3;
obj1.fun();
obj2.fun();
obj3.fun();
getch();
}
This program will generate the following output: -
该程序将生成以下输出:-
Value of a = 1
Value of a = 2
Value of a = 3
The same goes for globally declared static variable. The above code will generate the same output if we declare the variable a outside function void fun()
全局声明的静态变量也是如此。如果我们将变量声明为一个外部函数 void fun() 上面的代码将生成相同的输出
Whereas if u remove the keyword static and declare a as a non-static local/global variable then the output will be as follows: -
而如果您删除关键字 static 并将 a 声明为非静态局部/全局变量,则输出将如下所示:-
Value of a = 1
Value of a = 1
Value of a = 1