I'm writing a little C program that computes matrices (for learning purpose). The matrix is fed through arguments in the following form : "{{43,543.324,34},{43,432,87}}" The user doesn't give the dimensions.
I have solved this problem two times in two different ways:
- Short series of entangled if / else / mess
- Kind of a state machine doing one task at a time, much longer
Here they are, the first one is commented and the second one follows:
int matrix_fill(matrix * A, char * input)
{
size_t i, j;
float val;
/*
size_t input_len = strlen(input);
if (input[0] != '{' || input[input_len - 1] != '}') {
errno = EINVAL;
perror("matrix_fill");
exit(-1);
}
input[input_len - 1] = '\0';
input++, input_len -= 2;
i = 0;
while (*input != '\0') {
printf("input: %s\n", input);
j = 0;
if (*input == '{') {
input++;
while (1) {
val = strtof(input, &input);
printf("(%d,%d) = %f\n", i, j, val);
matrix_set(A, i, j, val);
j++;
if (*input == ',')
input++;
else if (*input == '}')
break;
else {
}
}
i++, input++;
A->m = i, A->n = j;
}
else if (*input == ',') {
input++;
}
else {
errno = EINVAL;
perror("matrix_fill");
exit(-1);
}
}
*/
enum {
start,
open,
read,
delim,
close,
end
} status = start;
while (*input != '\0') {
switch (status) {
case start:
if (*input != '{' || *(input + 1) != '{') {
errno = EINVAL;
goto error;
}
i = 0, input++;
status = open;
break;
case open:
j = 0, input++;
status = read;
break;
case read:
val = strtof(input, &input);
if (errno < 0) goto error;
matrix_set(A, i, j, val);
j++;
if (*input == ',')
status = delim;
else if (*input == '}')
status = close;
else {
errno = EINVAL;
goto error;
}
break;
case delim:
input++;
if (*input == '{')
status = open;
else
status = read;
break;
case close:
input++;
if (*input == ',')
status = delim;
else if (*input == '}')
status = end;
else {
errno = EINVAL;
goto error;
}
i++;
break;
case end:
input++;
A->m = i, A->n = j;
break;
}
}
return 0;
error:
perror("matrix_fill");
return -1;
}
Points I would like you to examine:
- Use of goto
- Length of the code
- Clarity
- Complexity of the solution vs complexity of the problem
I have had good results with both, but there might still be bugs. I'm more interested in your opinion about the design than the correctness.