4

{}以下は、関数内に存在 するサブ スコープ (または) ダミー スコープ (単に ) がスタック フレームの構造にどのように影響するかを理解するために参考にしたコードです。

#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 つは 内) を指定しても、コードが失敗しないのはなぜですか{}

4

2 に答える 2

2

ここでは、ハードウェア スタックは関係ありません。関数の入り口ですべてのローカル変数に対して一度だけ拡大し、関数の出口で一度だけ縮小するか、新しいローカル変数が定義され、それを囲む {} が残っているときに破棄されるたびに拡大および縮小できます。

関連するのは、変数の「可視性」です。

int main_scope=0;

{
    main_scope++;
    printf("main_scope++:(%d)\n",main_scope);
    // the main_scope variable that was assigned 0 is the most recent
    // visible declaration of main_scope.

    int main_scope=2;
    // now, the previous declaration of main_scope is obscured by the new one,
    // and so, you're going to access the new one
    printf("Value of redefined main_scope:(%d)\n",main_scope);
}

printf("Finally main_scope in %s:(%d)\n",__FUNCTION__,main_scope);
// the previous scope inside {} is left, so, main_scope is going to be
// the one, to which we assigned 0

外側/スーパースコープと同じ名前の内側/サブスコープでオブジェクトを定義することは完全に合法です。後者は、{} スコープの期間中は隠されます。

参考までに、for(;;)ステートメントの最初の式の内部など、変数定義が発生する可能性がある他の場所がいくつかありますfor (int i = 0; i < 10; i++) ...。その変数iは for の本体内でのみ表示され、別の を定義することで非表示にすることもできますi

于 2012-10-13T13:41:59.623 に答える
1

ローカル変数は外部変数を隠しmain_scopeます。

int main()
{
    int i=1;
    {

      int i=2;
      printf("%d", i);
      /* Whenever you use i here, it's always the local one that's used. 
      The outer i is hidden by the local i. But the local i will be deallocated 
      once the scope exits.*/
    } 
}

C では完全に合法です (これは C++ では違法であることに注意してください!)。

あなたの例では、確かに inner のスタック フレームが作成されmain_scopeますが、プログラムがその内部スコープを出ると割り当てが解除されます。

于 2012-10-13T13:42:12.527 に答える