Static variable

  1. A static variable inside a function keeps its value between invocations.
  2. A static global variable or a function is "seen" only in the file it's declared in

意思就是

1. 如果在function裡面定義一個Local的static變數時:

    每當離開function之後, 這個static變數的數值仍然會保留, 因為用static把這個變數定義的memory位置固定住了,

    也不會被別的變數所使用! 

   

可以參考下面的簡單範例, 非常容易理解:

#include <stdio.h>

void foo()
{
    int a = 10;
    static int sa = 10;

    a += 5;
    sa += 5;

    printf("a = %d, sa = %d\n", a, sa);
}


int main()
{
    int i;

    for (i = 0; i < 10; ++i)
        foo();
}

 

輸出結果:

a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60

 

這是一個實用的方法, 讓function可以不用global變數, 又可以永遠keep住上次執行後的數值, 但是如此一來也會造成

一些問題, 像是在多執行緒同時存取這個函數時, 相較於一般local變數, 這個static變數的值將變得難以掌握, 難以預測!

This is useful for cases where a function needs to keep some state between invocations, and you don't want to use global

variables. Beware, however, this feature should be used very sparingly - it makes your code not thread-safe and harder to understand.

 

 

2. 如果是定義一個Global的static變數(variable)或函數(function):

    這個變數(函數)只有在這個檔案內可以被存取(呼叫), 其他的檔案是看不到這個Global變數(函數)的, 也因此當其他檔案

    也定義相同名稱的變數(函數)時, 不會因為定義名稱相同而產生Compile錯誤!

 

    這就相當於C++中的private變數(函數)用途是一樣的, 最大的目的還是用來決定變數(函數)可以被誰使用, 若設定成static,

    多半是希望這些函數不被其他檔案看見並且呼叫(或者看見了也無法呼叫), 而有些變數(函數)為了要做成SDK或函式庫,類別

    庫, 讓第三方使用者能簡單使用而且不需要了解函式庫的內容, 就不會特別再加上static來修飾這個變數(函數)

 

 

arrow
arrow

    NoSleep 發表在 痞客邦 留言(0) 人氣()