patterncMinor
K&R 4-12 recursive converter int to string
Viewed 0 times
recursiveintstringconverter
Problem
The exercise is:
Adapt the ideas of printd to write a recursive version of itoa; that
is, convert an integer into a string by calling a recursive routine.
I wonder if I have correctly answered the question.
I presented it in a way it's not directly a converter but mostly. I'm a beginner so I don't know if I write some strange things. Could you please review my code?
Adapt the ideas of printd to write a recursive version of itoa; that
is, convert an integer into a string by calling a recursive routine.
I wonder if I have correctly answered the question.
# include
# define MAX 100
int itoa (char s[], int n)
{
static int i = 0;
if (n < 0) {
s[i++] = '-';
n = -n;
}
if (n / 10)
itoa (s, n / 10);
if (i < MAX-1)
s[i++] = n % 10 + '0';
else {
s[i] = '\0';
return 0;
}
return 1;
}
int main ()
{
int number = -123456789;
char string[MAX] = { 0 };
if (itoa(string, number))
printf("The string is : %s\n", string);
else
printf("Error : array limit reached\n");
}I presented it in a way it's not directly a converter but mostly. I'm a beginner so I don't know if I write some strange things. Could you please review my code?
Solution
No, this is not a correct solution. Since
It also fails to handle
You should never omit the "optional" braces for if, else, for, and while blocks. By doing so, you are contributing to future coding accidents. See this recent Apple security vulnerability and this quote from the author of jQuery:
I really dis-liked having unnecessary braces. This… unfortunate… style preference plagued us for quite a while and caused all sorts of avoidable logic errors.
i is static, the function will fail the second time it is used.It also fails to handle
INT_MIN correctly, since -INT_MIN will overflow an int.You should never omit the "optional" braces for if, else, for, and while blocks. By doing so, you are contributing to future coding accidents. See this recent Apple security vulnerability and this quote from the author of jQuery:
I really dis-liked having unnecessary braces. This… unfortunate… style preference plagued us for quite a while and caused all sorts of avoidable logic errors.
Context
StackExchange Code Review Q#94174, answer score: 5
Revisions (0)
No revisions yet.