My solution to string interpretation is pretty fast. However, I worry about repeated if (Len == 1)
. That might make the function bigger in the executable. How can I improve my function, to not be as redundant while checking if Len
is equal to 1?
#include <ctype.h>
signed char BoolFromStr(const char *const StrIn, register const unsigned char Len) {
if (!Len || Len > 5 || !StrIn) {
return -1;
}
switch (tolower(*StrIn)) {
case '0':
if (Len == 1) {
return 0;
}
break;
case 'f':
if (Len == 1 || (Len == 5 && !memcmp(Str+1, (const char[]){'a', 'l', 's', 'e'}, 4))) {
return 0;
}
break;
case 'n':
if (Len == 1 || (Len == 2 && Str[1] == 'o')) {
return 0;
}
break;
case '1':
if (Len == 1) {
return 1;
}
case 'y':
if (Len == 1 || (Len == 3 && !memcmp(Str+1, (const char[]){'e', 's'}, 2))) {
return 1;
}
break;
case 't':
if (Len == 1 || (Len == 4 && !memcmp(Str+1, (const char[]){'r', 'u', 'e'}, 3))) {
return 1;
}
break;
}
return -1;
}