2012-04-04 95 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,您都可以获得前柜台。

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,则它打印hello1

它然后递减计数器(--counter = 0),所以myFunction的:由于此的立即返回。

但计数器仍然递减,所以计数器= 0时它达到cout < <计数器< < endl;即使它与1