T
Tyler Smith
Hi,
I'm working through K & R, and I have a few questions about recursive
functions. I've solved the problem at hand, but my solution seems
clumsy. In particular, I suspect there must be a better way to allow
link each instance of the function to the array cell that it produces.
I've used a static variable, which is ok except that it requires an
extra variable to indicate whether or not the function call was the
original, or spawned by another instance of printd.
Also, I've written this as a void function - since it's directly
modifying the string, is there any value to returning the string, or
is it fine to allow the calling program to simply access the modified
string?
I hope this makes sense. The code is pasted below.
Thanks,
Tyler
#include <stdio.h>
void printd (int n, char s[], int new)
{
static int p;
p = new ? 0: p;
if (n< 0 ) {
s[p++]='-';
n = -n;
}
if (n/10)
printd(n/10, s, 0);
s[p++]= (n % 10 + '0');
}
int main (void)
{
char s[100];
printd(123, s, 1);
printf("string is %s\n", s);
printd(456, s, 1);
printf("string is %s\n", s);
}
I'm working through K & R, and I have a few questions about recursive
functions. I've solved the problem at hand, but my solution seems
clumsy. In particular, I suspect there must be a better way to allow
link each instance of the function to the array cell that it produces.
I've used a static variable, which is ok except that it requires an
extra variable to indicate whether or not the function call was the
original, or spawned by another instance of printd.
Also, I've written this as a void function - since it's directly
modifying the string, is there any value to returning the string, or
is it fine to allow the calling program to simply access the modified
string?
I hope this makes sense. The code is pasted below.
Thanks,
Tyler
#include <stdio.h>
void printd (int n, char s[], int new)
{
static int p;
p = new ? 0: p;
if (n< 0 ) {
s[p++]='-';
n = -n;
}
if (n/10)
printd(n/10, s, 0);
s[p++]= (n % 10 + '0');
}
int main (void)
{
char s[100];
printd(123, s, 1);
printf("string is %s\n", s);
printd(456, s, 1);
printf("string is %s\n", s);
}