変数には、定義の場所によって「有効範囲(スコープ)」が異なる。
省略 または auto:
一時的な変数。変数宣言時に何も明記しないと auto になる。
static :
一度初期化されると消去されない。初期化を一度だけ行う
extern:
他のモジュールで定義されていることを明示する
helloscope.c 変数の有効範囲を確認する例
#include <stdio.h>
int g=5;
void func(void){
int a = 2;
printf("func:a=%d\n",a);
printf("func:g=%d\n",g);
g=10;
}
int main(void){
int a = 3;
printf("main:a=%d\n",a);
printf("main(1):g=%d\n",g);
func();
printf("main(2):g=%d\n",g);
}
■実行結果
>helloscope.exe
main:a=3
main(1):g=5
func:a=2
func:g=5
main(2):g=10
hellostatic.c (記憶クラス確認例)
#include <stdio.h>
void func(void){
static int c=0;
c++;
printf("count=%d\n",c);
}
void main(void){
func();
func();
func();
}
■実行結果
>hellostatic.exe
count=1
count=2
count=3
helloscope.c hellostatic.c を作成し、メールで添付ファイルとして提出する。
提出先: K05025@center.shonan-it.ac.jp
締め切り:次回授業の前日