The implementation of the C programming language 2nd (ch4.10 recursion) is (parameter n cannot be the smallest integer ):
void printd(int n) { if (n < 0) { putchar('-'); n = -n; } if (n / 10) printd(n / 10); putchar(n % 10 + '0');}
The implementation of C traps and pitfalls (ch7.11 an example of portability problems) is similar:
void printnum(long n, void (*p)(int)) { if (n < 0) { (*p)('-'); n = -n; } if (n >= 10) printnum(n / 10, p); (*p)((int)(n % 10) + '0');}
From the compatibility perspective, Andrew Koenig believes that the last statement has a problem. '0' + 5 get '5'. It is assumed that the computer is implemented based on ANSI, and the characters '0' to '9' are continuous. so it should be changed:
(* P) ("0123456789" [(n % 10)]);
The prerequisite for correct execution of the two programs is that parameter n cannot be the smallest integer. otherwise, n =-N will cause overflow. changing the positive number symbol does not overflow, so Andrew Koenig changes the program to process only negative numbers (if the parameter is a positive number, change its symbol ):
void printneg(long n, void (*p)(int)) { if (n <= -10) printneg(n / 10, p); (*p)("0123456789"[-(n % 10)]);}void printnum(long n, void (*p)(int)) { if (n < 0) { (*p)('-'); printneg(n, p); } else printneg(-n, p);}
Here is another assumption: the value of N % 10 (n <0) is negative. however, the C language does not define the result symbol. Only the expression r = A % B can be guaranteed. When a> = 0 and B> 0, r> 0 exists, | r | <| B | (ch7.7 how does Division truncate ?). Therefore, you need to modify the printneg function:
void printneg(long n, void (*p)(int)) { long q; int r; q = n / 10; r = n % 10; if (r > 0) { r -= 10; ++q; } if (n <= -10) printneg(q, p); (*p)("0123456789"[-r]);}
The following is the execution result (Ubuntu 10.4.1 Linux, 32 bits ):
Printd (0x80000000): -- 214748364 (
Printnum (0x80000000, (void (*) (INT) putchar):-2147483648 references:
The C programming language 2nd (ch4.10 recursion)
C traps and pitfalls (ch7.11 an example of portability problems)