2012-04-04 7 views
2

私はこのコードを実行すると、出力は次のようになります。カウンタがインクリメントするのはなぜですか?

hello5 
hello4 
hello3 
hello2 
hello1 
0 
1 
2 
3 
4 

私はhello1まで理解が、私はそれが増加している理由を知りません。誰かが私にこれを説明することはできますか?それが増加していないです

#include <iostream> 
#include <iomanip> 
using namespace std; 

void myFunction(int counter) 
{ 
    if(counter == 0) 
     return; 
    else 
    { 
     cout << "hello" << counter << endl; 
     myFunction(--counter); 
     cout << counter << endl; 
     return; 
    } 
} 

int main() 
{ 
    myFunction(5); 

    return 0; 
} 

答えて

6

、あなただけの再帰呼び出し後の値を印刷している:パラメータは値渡しされる

cout<<"hello"<<counter<<endl; 
    myFunction(--counter); 
    cout<<counter<<endl; // <--- here 

ので、ローカル変数は、再帰呼び出しの内部で変更されません。私。 --counterのコピーを渡しています。呼び出し後、counterがその内部でどのように変更されても、exカウンタが取得されます。

3

あなたはこのように行く:

m1:Print "hello 5", 
     m2:Print "hello 4", 
       m3:Print "hello 3", 
        m4:Print "hello 2" 
         m5:Print "hello 1" 
          m6: -- RETURNS 
         m5:Print "0" -- -- FUNCTIONS CONTINUES AND ENDS 
        m4:Print "1" -- FUNCTIONS CONTINUES AND ENDS 
       m3:Print "2" -- FUNCTIONS CONTINUES AND ENDS 
     m2:Print "3" -- FUNCTIONS CONTINUES AND ENDS 
    m1:Print "4" -- FUNCTIONS CONTINUES AND ENDS 

、なぜそれが0を印刷していますか?これの理由:

cout<<"hello"<<counter<<endl; 
    myFunction(--counter); 
    cout<<counter<<endl; 

カウンタ= 1の場合、それは、次いで(--counter = 0)、MyFunctionのは非常にカウンタをデクリメント

hello1印刷( - カウンタ)。すぐに戻る

カウンタがまだデクリメントされているので、カウンタが0に達すると0になります。< <カウンタ< < endl;たとえそれが始まったとしても1

関連する問題