On 02/19/2018 11:17 AM, Collin L. Walling wrote:
How is this for a compromise?
- start num_idx at 1, provide comment as for why
- change while loop comment to explain we are "counting the
_indices_ _of_ _num_"
- str[num_idx] is assigned \0, and we also decrement num_idx in one
line
- in conversion loop, post decrement num_idx as it is used
char *uitoa(int num, char *str, int len)
{
int num_idx = 1; /* account for NULL */
The single-byte character is named NUL (while NULL refers to the 8- or
4-byte pointer value).
int tmp = num;
assert(str != NULL, "uitoa: no space allocated to store string");
/* Count indices of num */
while ((tmp /= 10) != 0)
num_idx++;
/* Check if we have enough space for num and null */
and again
assert(len > num_idx, "uitoa: array too small for conversion");
str[num_idx--] = '\0';
/* Convert int to string */
while (num_idx >= 0) {
str[num_idx--] = num % 10 + '0';
num /= 10;
}
return str;
Otherwise, it seems readable to me.
}
--
Eric Blake, Principal Software Engineer
Red Hat, Inc. +1-919-301-3266
Virtualization: qemu.org | libvirt.org