• Static / Const 的概念


    C/C++/Java Static / Const 的概念
    这里以C为准,其他语言类似。
    Static变量是指分配不变(只可分配一次,以后再分配就无效了。)的变量 -- 它的存活寿命或伸展域可以贯穿程序运行的所有过程。这个概念与“ephemeral-短命的”,分配即变的,变量恰恰相反。常常被人们称作的局部变量就是分配即变的。分配即变的变量的存储空间的分配或者回收都是在Stack上完成。相反,分配不变变量的存储空间实在heap memory上动态分配的。
    当一个程序被加载到内存,Static变量被存放在程序的地址空间的数据区(如果已初始化了),或者BBS区(BBS Segment)(如果没有被初始化)。 并且在加载之前就被存放在对应的对象文件的区域。
    Static 关键字在 C 语言和其他相关语言中都是指这个静态分配的意思或类似意思。

    --- 作用域 ---
    Scope[edit]
    See also: Variable (computer science)#Scope and extent
    In terms of scope and extent, static variables have extent the entire run of the program, but may have more limited scope. A basic distinction is between a static global variable, which is in scope throughout the program, and a static local variable, which is only in scope within a function (or other local scope). A static variable may also have module scope or some variant, such as internal linkage in C, which is a form of file scope or module scope.
    In object-oriented programming there is also the concept of a static member variable, which is a "class variable" of a statically defined class – a member variable of a given class which is shared across all instances (objects), and is accessible as a member variable of these objects. Note however that a class variable of a dynamically defined class, in languages where classes can be defined at run time, is allocated when the class is defined and is not static.
     --- 程序示例 Example ---
    An example of static local variable in C:

    #include <stdio.h>
     
    void func() {
            static int x = 0; // x is initialized only once across three calls of func()
            printf("%d
    ", x); // outputs the value of x
            x = x + 1;
    }
     
    int main(int argc, char *argv[]) {
            func(); // prints 0
            func(); // prints 1
            func(); // prints 2
            return 0;
    }


  • 相关阅读:
    《30天自制操作系统》17_day_学习笔记
    《30天自制操作系统》18_day_学习笔记
    湖大OJ-实验E----可判定的DFA的空问题
    湖大OJ-实验C----NFA转换为DFA
    《30天自制操作系统》16_day_学习笔记
    《30天自制操作系统》19_day_学习笔记
    《30天自制操作系统》15_day_学习笔记
    《30天自制操作系统》14_day_学习笔记
    [Leetcode Week11]Kth Largest Element in an Array
    [Leetcode Week10]Minimum Time Difference
  • 原文地址:https://www.cnblogs.com/sonictl/p/6735627.html
Copyright © 2020-2023  润新知