영어로 읽는 코딩

27 [C] 재귀함수

Recursion

 

C functions may be used recursively; that is, a function may call itself either directly or indirectly. Consider printing a number as a character string. As we mentioned before, the digits are generated in the wrong order: low-order digits are available before high-order digits, but they have to be printed the other way around.

 

There are two solutions to this problem. One is to store the digits in an array as they are generated, then print them in the reverse order. The alternative is a recursive solution, in which printd first calls itself to cope with any leading digits, then prints the trailing digit. Again, this version can fail on the largest negative number.

 

#include <stdio.h>

/* printd: print n in decimal */

void printd(int n)

{

    if (n < 0) {

           putchar ('-');

           n = -n;

    }

    if (n / 10)

           printd(n / 10);

    putchar (n % 10 + '0');

}

 

When a function calls itself recursively, each invocation gets a fresh set of all the automatic variables, independent of the previous set. Thus in printd(l23) the first printd receives the argument n = 123. It passes 12 to a second printd, which in turn passes 1 to a third. The third-level printd prints 1, then returns to the second level. That printd prints 2, then returns to the first level. That one prints 3 and terminates.

 

[The C Programming Language p.86-87]

댓글

댓글 본문
작성자
비밀번호
버전 관리
Yoo Moon Il
현재 버전
선택 버전
graphittie 자세히 보기