auの日記

プログラミング初心者の日記。(auはハンドルネームです)

C言語の自由変数

auです。
学校の資料をみていたら自由変数という言葉がでていて、気になったので調べてみました。

自動変数とは

自動変数とは、ようはローカル変数のことで関数の中の{}で囲まれた部分で宣言した変数は、その中でのみ有効になるというものです。要はローカル変数のことでした。
aとbをmain関数の中で与えて、sub関数で引き算をした後にmain関数に戻り値を渡して出力するプログラムです。

#include <stdio.h>

int sub(int d, int e) {  // {}これがブロック1
    int f = d - e;
    return f;
}  // ブロック1

int main(void) {  // mainの{}ブロック2
    int a = 3;
    int b = 2;
    int c; 
    
    c = sub(a, b);
    printf("C = %d\n", c);
    return 0; 
}  // ブロック2

// 実行結果
c = 1

int a, b, cはmain関数の中でのみ有効。
int d, e, fはsub関数でのみ有効です。

比較のために別のプログラムを組みました。
main関数の中にもう一つブロック({ })をつくり、そこでint型のbを宣言しました。

#include <stdio.h>

int sub(int d, int e) {  // {}これがブロック1
    int f = d - e;
    return f;
}  // ブロック1

int main(void) {  // mainの{}ブロック2
    int a = 3;
    int c; 
    {  // ブロック3
        int b = 2;
    } // ブロック3
    
    c = sub(a, b);
    printf("C = %d\n", c);
    return 0; 
}  // ブロック2

// 実行結果
automatic.c: In function ‘main’:
automatic.c:15:16: error: ‘b’ undeclared (first use in this function)
     c = sub(a, b);
                ^
automatic.c:15:16: note: each undeclared identifier is reported only once for each function it appears in

エラーが起きました。
自動変数=ローカル変数、そのブロックの中でしか動作のすることができない変数のことでした。