So I have the following code in C, a really straight forward hex string to integer conversion function:
#include <stdio.h>
#include <string.h>
int hexatoi(char *str, int *to) {
int num = 0,
i = 0,
len = strlen(str),
t;
char c, b;
if (len < 2 || len > 8 || str[0] != '0' || str[1] != 'x') {
return 1;
}
while (str[i] != '\0') i++;
i--;
while(i > 1) {
c = str[i];
if (c >= '0' && c <= '9')
b = c - '0';
else if (c >= 'a' && c <= 'z')
b = c - 'a' + 10;
else if (c >= 'A' && c <= 'Z')
b = c - 'A' + 10;
else
return 1;
num |= (int)b << (len-1-i)*4;
i--;
}
*to = num;
return 0;
}
int main(int argc, char *argv[]) {
int i;
if (hexatoi(argv[1], &i)) {
printf("Malformed input");
return 1;
}
printf("%d\n", i);
return 0;
}
and I'm wondering what the best way to say "your string is malformed" is. As you can see from the code the function takes a string and a pointer to an integer and assigns the result of the conversion at the pointer, using the return value to indicate if there was an error. I really hate this approach, taking a pointer and mutating it feels dirty to me. I want to just return the converted number but there's no possible value that couldn't be a valid output.
My other idea was to return a struct that has the value and a "there was an error" field, but I've never seen that before and feel like it would look pretty weird in C.
Is there a better way of handling this kind of situation.