ページ 11

変数のスコープについて

Posted: 2022年5月19日(木) 20:48
by conori
#include <stdio.h>

int a = 1;

void sub1(int);
void sub2();

int main()
{
int b = 2;

sub1(b);

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

return 0;
}

void sub1 (int c)
{
sub2();
printf("%d\n" , c);
}

void sub2()
{
printf("%d\n" , a);
}


で何故printf("%d\n" , a);が最初に実行されるのでしょうか?何故このコードは全部下から実行されるのでしょうか

Re: 変数のスコープについて

Posted: 2022年5月19日(木) 22:14
by box
変数のスコープとは全然関係ないです。
関数の呼び出し・実行順は
1)mainの先頭でsub1を呼んでいる。
2)sub1の先頭でsub2を呼んでいる。
3)sub2でaの値を出力している。
4)sub1に戻り、cの値を出力している。
5)mainに戻り、bの値を出力している。
ってだけです。