{}
以下は、関数内に存在 するサブ スコープ (または) ダミー スコープ (単に ) がスタック フレームの構造にどのように影響するかを理解するために参考にしたコードです。
#include <stdio.h>
int main()
{
int main_scope=0; /*Scope and life time of the variable is throughout main*/
{
//From below two statements I assume that there
//is no seperate "stack frame" created for just
//braces {}.So we are free access (scope exists) and
//modify (lifetime exists) the variable "main_scope"
//anywhere within main
main_scope++;
printf("main_scope++:(%d)\n",main_scope);
//I expected this statement to throw an error saying
//"Multiple definition for "main_scope".But it isn't????
int main_scope=2;
printf("Value of redefined main_scope:(%d)\n",main_scope);
}
printf("Finally main_scope in %s:(%d)\n",__FUNCTION__,main_scope);
return 0;
}
サンプル出力
main_scope++:(1)
Value of redefined main_scope:(2)
Finally main_scope in main:(1)
以上の行動から、以下のように推測します。
- スコープのスタック フレームの作成はありません
{}
。 - このようにして
auto
、宣言/定義された変数とmain
サブスコープ内の変数{}
は同じスタック フレームを共有します。 - したがって、 で宣言/定義された変数は
main
、関数内のどこでも (サブ スコープ内であっても) 自由にアクセスできます。 - 一方、サブスコープで宣言/定義された変数は、ブロックの外でそのスコープを失います。ただし、スタックフレームが存在する限り、その有効期間は有効です。
質問:上記の点が正しければ、同じ変数の複数の定義 (1 つは 内main
、もう1 つは 内) を指定しても、コードが失敗しないのはなぜですか{}
。