mdh said:
Sorry..should have included that.
#include <stdlib.h>
void itoa_recursively(int n, char *s){
static char *p;
p = s;
if ( n / 10 )
itoa_recursively(n / 10, s);
else
if ( n < 0)
*p++ = '-';
*p++ = abs(n) % 10 + '0';
*p = '\0';
}
Well, here is my naive ( and incorrect) way of understanding this. I
**thought!!** that once the ptr *p is initialized, then subsequent
iterations through the function would be able to use the retained
information for placing the digits correctly in "s".
The only difference between a static variable defined inside a
function and one defined at file scope is visibility.
If you moved the declaration of ``p'' outside your function, making it
a global variable, but leaving the assignment "p = s;" where it is,
the behavior of your program would not change -- but it might be a
little easier to understand. The value you assign to p isn't
available within an inner recursive call. *But* the value assigned to
``p'' by your inner recursive call *is* available in the outer call.
With line numbers:
1 #include <stdlib.h>
2 void itoa_recursively(int n, char *s){
3 static char *p;
4 p = s;
5 if ( n / 10 )
6 itoa_recursively(n / 10, s);
7 else
8 if ( n < 0)
9 *p++ = '-';
10 *p++ = abs(n) % 10 + '0';
11 *p = '\0';
12 }
At line 4, you assign a value to ``p''. At line 6, you call
itoa_recursively(), assigning some new value to ``p''. At lines 10
and 11, the value of ``p'' isn't the value assigned at line 4, it's
the value assigned somewhere within the recursive call.
I'm too lazy to trace through the logic of your program, but it's not
obviously wrong.
I used Tondo and Gimpel's answer to 4-12 as a basis for this. They
declared a static variable which was used to keep the information
about the position of the next digit to be added, as in:
#include <stdlib.h>
void itoa_recursively(int n, char *s){
static int i;
if ( n / 10 )
itoa_recursively(n / 10, s);
else {
i = 0;
if ( n < 0)
s[i++] = '-'; }
s[i++] = abs(n) % 10 + '0';
s = '\0';
Note that T&G's version doesn't clobber the static variable every time
it enters the function. (I'm not saying it should or shouldn't.)