靜態變量的生命週期貫穿整個程式執行期,它的記憶體被獨立配置在所謂的靜態記憶體區。所有靜態變量若不显式賦值,都會被自動初始化為 0,不論是結構體還是其他型別。
靜態變量的初始化又分兩類:
int a = 1;double a = sqrt(2);先釐清三個概念:「內部」表示不能被其他檔案引用,「外部」表示可被其他檔案引用;「全域」表示可見範圍為整個檔案,「局部」表示可見範圍僅限該程式區塊。
int test(void)
{
static int i = 1;
.....
}
有效範圍僅限該函式區塊,外部檔案完全無法觸及。
int i = 1;
int test(void)
{
....
}
可見範圍為本檔案,且對外開放;其他檔案可用 extern int i; 引用。
static int i = 1;
int test(void)
{
....
}
可見範圍為本檔案,但不對外開放,其他檔案寫 extern int i; 是行不通的。順帶一提,extern int i; 只是宣告,不能初始化,也不會配置任何記憶體——真正的空間已在別處配置完成。
只有佔有確切記憶體空間的表達式才能作為左值:
int a = 1; int *p; p = &a; // 可以 *p = 1; // 可以
而 a + b = 5; 這類寫法不成立,因為 a + b 只是一段暫時的結果,並非具名記憶體。
既然靜態記憶體區在整個程式期間都存在,C/C++ 足夠靈活,我們完全可以定義指標去訪問它。下面這段程式除了示範這一點,也順帶示範了 flexible array member 的用法。
// t1.h
#include <iostream>
using namespace std;
#ifndef TEST_H__
#define TEST_H__
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct chain
{
char address[]; // 彈性陣列
} CM;
typedef struct mc
{
int id;
char name[20];
CM* adr;
} CHC;
#define LEN_S strlen(max_address) + sizeof(CM) + 3
#define LEN_MAX strlen(max_address)
CM* finps(CHC* ins);
void fshows(const CHC* ins);
int** stre(void);
#endif
// t3.cpp
#include <iostream>
#include "t1.h"
using namespace std;
static int st1 = 1;
static int st2 = 2;
int** stre(void)
{
static int* p[2];
p[0] = &st1;
p[1] = &st2;
return p; // 回傳指向指標的指標
}
CM* finps(CHC* ins)
{
char max_address[80];
static CM* ck;
cout << "please input id:" << endl;
cin >> ins->id;
cin.get();
cout << "please input name:" << endl;
cin.getline(ins->name, 19);
cout << "please input your address" << endl;
cin.getline(max_address, 79);
ck = (CM*) malloc(LEN_S);
ins->adr = ck;
strcpy(ck->address, max_address);
return ck;
}
void fshows(const CHC* ins)
{
cout << "your information is:" << endl;
cout << ins->id << endl;
cout << ins->name << endl;
cout << ins->adr->address << endl;
}
// t2.cpp
#include <iostream>
#include "t1.h"
using namespace std;
int main(void)
{
CHC ins;
CM* dt;
int** p;
dt = finps(&ins);
fshows(&ins);
free(dt);
p = stre();
cout << "access static values from pointer:" << endl;
cout << **p << endl; // st1
cout << **(p + 1) << endl; // st2
}
這裡的關鍵是 stre():函式內用一個靜態指標陣列保存 st1、st2 的位址,再回傳指向該陣列的指標。因此在 main 中只要 **p、**(p+1) 就能讀到這兩個內部全域靜態變量——宣告上它們是私有的,實際上仍被取用了。
$ g++ t2.cpp t3.cpp $ ./a.out please input id: 1 please input name: gaopeng please input your address chongqing your information is: 1 gaopeng chongqing access static values from pointer: 1 2
這也提醒我們:static 主要是編譯期的連結與可見性約束,而非真正的記憶體保護。