Hi everyone,
I just want to get feedback on this code. I've been studying C seriously for a couple of years now, using K&R. Any comments?
Code:
/* exercise 3-4 from K&R 2
Write a version of itoa that accepts three arguments instead of two.
The third argument is a minimum field width; the converted number must
be padded with blanks on the left if necessary to make it wide enough.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define BASE 10
static char *
reverse(char *s, unsigned int j)
{
unsigned int i = 0;
assert (j > 0);
--j;
while (i < j)
{
char temp = s[i];
s[i] = s[j];
s[j] = temp;
++i;
--j;
}
return s;
}
static char *
my_itoa(int n, char s[], unsigned int min)
{
unsigned int negative = (n < 0);
unsigned int i = 0;
div_t d;
assert(BASE >= 2 && BASE <= 10);
assert(s);
do
{
int digit;
d = div(n, BASE);
digit = d.rem;
if (negative)
{
digit = -digit;
if (digit < 0)
digit += BASE;
}
s[i] = digit + '0';
assert(s[i] >='0' && s[i] <= (BASE - 1 + '0'));
n = d.quot;
++i;
}
while (n != 0);
if (negative)
{
s[i] = '-';
++i;
}
while (i < min)
{
s[i] = ' ';
++i;
}
reverse(s, i);
s[i] = 0;
return s;
}
int main(void)
{
char s[100];
printf("my_itoa(12345, s, 5) == \n%s\n", my_itoa(12345, s, 5));
printf("my_itoa(-67890, s, 10) == \n%s\n", my_itoa(-67890, s, 10));
printf("my_itoa(-32132145, s, 3) == \n%s\n", my_itoa(-32132145, s, 3));
return 0;
}