6

このプログラムの出力の背後にある理由を説明できる人はいます0 0 0 0 0か?

ここでは、static variable var関数呼び出しによって値が変更されない a を使用しています。の値はvar4, 3, 2, 1再帰呼び出し中です。がゼロになると、再帰は終了し、制御はステートメントvarに移ります。printf

出力が ではないのはなぜ1,2,3,4ですか?

 main(){ 
      static int var=5;
      if(--var)
        main();
      printf(" %d ",var);
 }

if 条件を使用するとvar--、プログラムの出力は次のようになり-1 -1 -1 -1 -1 -1ます。

4

3 に答える 3

11

In your recursion call printf() executes when main() returns. And because var is a static variable its value remain 0 (last value = 0 same for all function call)

Note if() condition false when var becomes 0 (last value, after main(); call you don't change var - notice diagram).

Hope following diagram will help you to understand (read comments):

main() <---------------+
{                      |
  static int var=5;    | <----"Declared only one/first time with value 5"
  if(--var)            |
 ---- main(); ---------+ // called if var != 0 
 |             // main called for var = 4, 3, 2, 1  
 |// recursion stooped     
 |// return with 0 value 
 |// now no operation applied on `var` so it remain 0 
 +--> printf(" %d ",var);  // called when return ed  
}

Remainder life of static function is till program terminates (so values not loss), and Scope is within function.

14.1.6 Static Variables

The scope of static automatic variables is identical to that of automatic variables, i.e. it is local to the block in which it is defined; however, the storage allocated becomes permanent for the duration of the program. Static variables may be initialized in their declarations; however, the initializers must be constant expressions, and initialization is done only once at compile time when memory is allocated for the static variable*.

Second question:

Again if you use var-- then your output will be -1 -1 -1 -1 -1 -1?

Suppose if your condition will be var-- then if() condition fist checks true or false before decrement --. (because in expression var--, -- is postfix).
And because if() breaks when var == 0 then recursive call stops and function returns with decremented value from 0 to -1. And because after return var doesn't change hence output is -1 for all.

于 2013-07-22T10:57:16.133 に答える
1

静的変数は、その寿命がプログラムの寿命と同じままである変数です。静的変数は一度初期化されます。変数の値は、システム コールごとに変更されます。変数を static として宣言していないと、無限再帰が発生し、セグメンテーション違反が発生します。

于 2013-07-22T11:34:54.207 に答える