I understand there are few places a goto
could be useful, such as embedded for loops or cleanup for multiple function exit points. I was wondering if this could be an acceptable place to do so.
I'm building a regex engine and am using a switch statement to handle each individual character of input. Anything that is not a meta-character goes to the switch's default
.
When I read a backslash (\
), I want the next character to be escaped and treated literal, i.e. jump directly to the switch's default
case. So I thought would it be okay to just goto
to the default case by adding another label? Or should I just go the conventional way and separate it into a function?
for(const char* c = regex; *c; c++){
if(*c == '\\' && *++c)
goto literal;
switch(*c){
case '|':
...
case '*':
...
...
default: literal:
...
}
}
It's at least semi-legitimate, but you can write essentially the same code without a goto
fairly easily:
for (const char* c = regex; *c; c++)
{
switch (*c)
{
case '|':
...
case '*':
...
...
case '\\':
if (*++c == '\0')
…report backslash followed by null, probably an error…
/*FALLTHROUGH*/
default:
...
}
}
Note that you'd need a case
in your original switch
to deal with backslash followed by EOS ('\0'
) anyway.