zoukankan      html  css  js  c++  java
  • [轉]C語言的static用法

    1. 使用在全域變數或全域函式 (Global variable & Global function)
    讓該變數(或該函式)的可視範圍只侷限在該檔案內,其他的 .c檔看不到此變數(或函式)的存在。
    既使其他檔案用extern宣告也看不到!套句行話來說,他把Global的變數或函數變成了「internal linkage」,當Linker在找symbol時是會忽略它的。
    (在C++中也相容這種用法,不過被視為比較不建議的舊的用法,C++比較建議使用unnamed namespace。)

    使用時機:當此全域變數(或全域函式)不想被其他檔案引用和修改時,或者不同檔案可以使用相同名字的全域變數(或全域函式)而不會產生命名衝突。

    2. 使用在函式內的區域變數 (Local variable)
    因為區域變數預設就是動態變數,而在區域變數前加上static修飾字則會將變數由動態(dynamic)變數轉為靜態(static)變數,靜態變數的壽命(lifetime)與動態變數不同,靜態變數會一直存在,直到程式結束為止。

    使用時機:這種很適合用來做統計次數的功能(某函式被呼叫幾次),例如以下的代碼...

    #include<stdio.h>
    int ff(){
    int ans = 0;
    return ans++;
    }
    int gg(){
    static int ans = 0;
    return ans++;
    }
    int main(){
    printf("ff: %d %d %d\n", ff(),ff(),ff());
    printf("ff: %d %d %d\n", gg(),gg(),gg());
    }

    output:

    ff: 0 0 0
    ff: 2 1 0

    -------

    const is a promise that you will not try to modify the value once set.

    static variable means that the object's lifetime is the entire execution of the program and it's value is initialized only once before the program startup. All statics are initialized if you do not explicitly set a value to them.The manner and timing of static initialization is unspecified.

    C99 borrowed the use of const from C++. On the other hand, static has been the source of many debates (in both languages) because of its often confusing semantics.

    Also, with C++0x, the use of the static keyword is deprecated when declaring objects in namespace scope will be deprecated.

    The longer answer: More on the keywords than you wanted to know (right from the standards)

  • 相关阅读:
    C++ 多线程
    C++ 信号处理
    首页流量监控代码
    macro-name replacement-text 宏 调试开关可以使用一个宏来实现 do { } while(0)
    color depth 色彩深度 像素深度
    数据更新 数据同步 起始点 幂等同步历史数据
    获取当前调用函数名 方法名
    版本号风格为 Major.Minor.Patch
    query_string查询支持全部的Apache Lucene查询语法 低频词划分依据 模糊查询 Disjunction Max
    Cutoff frequency
  • 原文地址:https://www.cnblogs.com/bittorrent/p/2742360.html
Copyright © 2011-2022 走看看