中央論壇 - CENTER BBS

標題: C的儲存類別 [打印本頁]

作者: f66666602    時間: 2007-9-4 09:01
標題: C的儲存類別
( auto variable )l













































































l


Example 1:
l

main
( )
        {
           int x=1;
           
inner( );
           printf("%d\n",x);
        }
l
         
inner( )
        {
           int x=2;
           printf("%d\n",x);
        }

l
( static variable)靜 態 變 數 與 自 動 變 數 一 樣 , 是 某 特 定 函 數 內 的 區 域 性 變 數 , 但靜 態 變 數 的 值 不 會 因 函 數 的執 行 結 束 而 消 失 。


靜 態 變 數 的 宣 告 如 下 所 示 :


{

static int a;

static int b=12345;

static char c;

static float d=13.45;

.

.

.

}

Example 1: main()
{

increment();


increment
();

increment();

}



increment()

{

int x=0;

x=x+1;

printf("%d\n",x);

}
Result = ?????
Example 2: main()
{

increment();


increment
();

increment();

}

increment()

{

static int x=0;

x=x+1;

printf("%d\n",x);

}
Result = ?????
l
( extern variable)外部 變 數 和 前 面 所 提 到 的 變 數 不 同 。 外 部 變 數 的 有 效 範 圍 不 是 區 域 性 , 而 是 整 體 性 ( global ) , 外 部 變 數 定 義 在 任 何 函 數 的 外 面 , 表 示 可 以 被 其 他 函 數 所 共 用 。


Example 1:



int x=123;


main()

{

printf("%d\n",x);


}

Result =
?????

Example 2:



int
x=123;

main()

{

int x=321;

printf("%d\n",x);

}

Result =
?????



Example 3:

#include < stdio.h >
#include "extern.c"



int x=123;


main()

{

printf("%d\n",x);

run1();

run2();


}


run1()

{

printf("%d\n",x);

}

extern.c 內 容 如 下 :



#include < stdio.h >


run2()

{

extern int x;

printf("%d\n",x);

}

Result =
?????


/* ======================================== */
/*
程式實例:


*/

/*
局部(local)和整體(Global) 變數



*/
/* ======================================== */
#include <stdio.h>

int step = 10;
/* 整體變數宣告 */
int count = 5;
/* 整體變數宣告 */

/* ---------------------------------------- */
/*
將變數值加一
*/
/* ---------------------------------------- */
void increment()
{

int step = 0;


/* 局部變數 step 宣告 */


step++;
/* 局部變數加一 */

count++;
/* 整體變數加一 */

printf(" 副程序
%2d
%2d
\n",step, count);
}

/* ---------------------------------------- */
/*
主程式
*/
/* ---------------------------------------- */
void main()
{

int count = 0;


/* 局部變數宣告 */


count++;
/* 局部變數加一 */

step++;
/* 整體變數加一 */

printf(" 程序名
STEP
COUNT
\n");

increment();
/* 副程序呼叫 */

printf(" 主程序
%2d
%2d
\n",step, count);
}/* ======================================== */


執行結果

程序名
STEP
COUNT
副程序
1
6
主程序
11
1







歡迎光臨 中央論壇 - CENTER BBS (https://centerbbs.com/) Powered by Discuz! X3