在c和c++中,静态、自动、全局变量和局部变量之间的差异。

时间:2021-12-31 16:48:38

I’ve a bit confusion about static, auto, global and local variables.

我对静态、自动、全局变量和局部变量有一些困惑。

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.

在我读到的某个地方,静态变量只能在函数中访问,但函数返回后它们仍然存在(保留在内存中)。

However, I also know that a local variable also does the same, so what is the difference?

但是,我也知道一个局部变量也是一样的,那么区别是什么呢?

6 个解决方案

#1


79  

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.
  • 存储持续时间,它决定何时创建和销毁变量。

Local variables (pedantically, variables with block scope) are only accessible within the block of code in which they are declared:

局部变量(pedan,带有块作用域的变量)只能在声明的代码块中访问:

void f() {
    int i;
    i = 1; // OK: in scope
}
void g() {
    i = 2; // Error: not in scope
}

Global variables (pedantically, variables with file scope (in C) or namespace scope (in C++)) are accessible at any point after their declaration:

全局变量(pedan,带有文件范围的变量(在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++中,情况更加复杂,因为名称空间可以被关闭和重新打开,而且除了当前的名称空间之外,还可以访问其他范围,并且名称也可以有类范围。但这是非常离题的。

Automatic variables (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.

自动变量(pedan,带有自动存储时间的变量)是局部变量,当执行离开它们的范围时,它们的生命周期结束,在重新输入范围时重新创建。

for (int i = 0; i < 5; ++i) {
    int n = 0;
    printf("%d ", ++n);  // prints 1 1 1 1 1  - the previous value is lost
}

Static variables (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 linkage so 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.

注意,静态关键字除了静态存储持续时间外,还有各种含义。在全局变量或函数上,它赋予它内部链接,使它不能从其他翻译单元访问;对于c++类成员,这意味着每个类有一个实例,而不是每个对象一个实例。同样,在c++中,auto关键字不再意味着自动存储持续时间;它现在意味着自动的类型,从变量的初始化。

#2


11  

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.

首先,我说你应该谷歌,因为它在很多地方都有详细的定义这些变量只存在于创建它们的特定函数中。它们对其他函数和主程序都是未知的。因此,它们通常是使用堆栈实现的。创建它们的函数完成后,局部变量就不再存在了。每当执行一个函数或调用一个函数时,就会重新创建它们。可以通过包含程序的任何函数访问全局变量。它们是通过将内存位置与变量名关联来实现的。如果函数被收回,它们就不会被重新创建。

/* 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++中,当执行到达声明的位置时调用自动变量的构造函数。当它到达给定程序块的末尾时调用析构函数(程序块被花括号包围)。该特性通常用于管理资源分配和分配,比如打开和自动关闭文件或释放内存。看到*

#3


4  

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;
}

#4


3  

Local variables are non existent in the memory after the function termination.
However static variables remain allocated in the memory throughout the life of the program irrespective of whatever function.

函数终止后,内存中不存在局部变量。然而,静态变量在程序的整个生命周期中仍然被分配,不管它有什么功能。

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.

此外,在您的问题中,静态变量可以在类或函数范围内声明,也可以在全局名称空间或文件范围内声明。它们从头到尾分配了内存,这只是初始化,迟早会发生。

#5


3  

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.

在C和c++中,静态是一个重载的词。函数上下文中的静态变量是在调用之间保持其值的变量。它们存在于程序的持续时间。

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++中是不同的。C中的auto是指定局部变量的(多余的)方法。在c++ 11中,auto现在用于自动派生一个值/表达式的类型。

#6


2  

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()

全局声明的静态变量也是如此。如果我们声明变量a外部函数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: -

然而,如果删除关键字静态并声明a为非静态局部/全局变量,那么输出将如下:-。

Value of a = 1
Value of a = 1
Value of a = 1

#1


79  

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.
  • 存储持续时间,它决定何时创建和销毁变量。

Local variables (pedantically, variables with block scope) are only accessible within the block of code in which they are declared:

局部变量(pedan,带有块作用域的变量)只能在声明的代码块中访问:

void f() {
    int i;
    i = 1; // OK: in scope
}
void g() {
    i = 2; // Error: not in scope
}

Global variables (pedantically, variables with file scope (in C) or namespace scope (in C++)) are accessible at any point after their declaration:

全局变量(pedan,带有文件范围的变量(在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++中,情况更加复杂,因为名称空间可以被关闭和重新打开,而且除了当前的名称空间之外,还可以访问其他范围,并且名称也可以有类范围。但这是非常离题的。

Automatic variables (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.

自动变量(pedan,带有自动存储时间的变量)是局部变量,当执行离开它们的范围时,它们的生命周期结束,在重新输入范围时重新创建。

for (int i = 0; i < 5; ++i) {
    int n = 0;
    printf("%d ", ++n);  // prints 1 1 1 1 1  - the previous value is lost
}

Static variables (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 linkage so 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.

注意,静态关键字除了静态存储持续时间外,还有各种含义。在全局变量或函数上,它赋予它内部链接,使它不能从其他翻译单元访问;对于c++类成员,这意味着每个类有一个实例,而不是每个对象一个实例。同样,在c++中,auto关键字不再意味着自动存储持续时间;它现在意味着自动的类型,从变量的初始化。

#2


11  

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.

首先,我说你应该谷歌,因为它在很多地方都有详细的定义这些变量只存在于创建它们的特定函数中。它们对其他函数和主程序都是未知的。因此,它们通常是使用堆栈实现的。创建它们的函数完成后,局部变量就不再存在了。每当执行一个函数或调用一个函数时,就会重新创建它们。可以通过包含程序的任何函数访问全局变量。它们是通过将内存位置与变量名关联来实现的。如果函数被收回,它们就不会被重新创建。

/* 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++中,当执行到达声明的位置时调用自动变量的构造函数。当它到达给定程序块的末尾时调用析构函数(程序块被花括号包围)。该特性通常用于管理资源分配和分配,比如打开和自动关闭文件或释放内存。看到*

#3


4  

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;
}

#4


3  

Local variables are non existent in the memory after the function termination.
However static variables remain allocated in the memory throughout the life of the program irrespective of whatever function.

函数终止后,内存中不存在局部变量。然而,静态变量在程序的整个生命周期中仍然被分配,不管它有什么功能。

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.

此外,在您的问题中,静态变量可以在类或函数范围内声明,也可以在全局名称空间或文件范围内声明。它们从头到尾分配了内存,这只是初始化,迟早会发生。

#5


3  

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.

在C和c++中,静态是一个重载的词。函数上下文中的静态变量是在调用之间保持其值的变量。它们存在于程序的持续时间。

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++中是不同的。C中的auto是指定局部变量的(多余的)方法。在c++ 11中,auto现在用于自动派生一个值/表达式的类型。

#6


2  

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()

全局声明的静态变量也是如此。如果我们声明变量a外部函数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: -

然而,如果删除关键字静态并声明a为非静态局部/全局变量,那么输出将如下:-。

Value of a = 1
Value of a = 1
Value of a = 1