Understanding recursion in the beer bottle example

后端 未结 7 1409
生来不讨喜
生来不讨喜 2020-12-21 01:37

I am practicing recursion in C on my own and I found this example online. However there is one thing I don\'t understand.

void singSongFor(int numberOfBottle         


        
7条回答
  •  盖世英雄少女心
    2020-12-21 01:47

    Note that the last printf uses the numberOfBottles variable, and that is never modified. So upon returning from printing oneFewer bottles, it will print the recycling text with numberOfBottles. Remember that there is one different incarnation of the local variables per each call to the function.

    It can be seen easier if you indent the calls to the functions:

    4 bottles of beer on the wall...
      3 bottles of beer on the wall...
        2 bottles of beer on the wall...
          1 bottles of beer on the wall...
            There are simply no more bottles of beer on the wall.
          Put a bottle in the recycling, 1 empty bottles in the bin.
        Put a bottle in the recycling, 2 empty bottles in the bin.
      Put a bottle in the recycling, 3 empty bottles in the bin.
    Put a bottle in the recycling, 4 empty bottles in the bin.
    

    Now, each line that begins in the same column is written from the same call of the function. Do you see how the number of bottles and recycling coindice? That's because both use the same variable: numberOfBottles.

提交回复
热议问题