Consider the following code:
const char *s = "a b c d !";
const char *p = s;
top:for(; *p; p++) {
switch(*p) {
case 0x20:
case '\n':
goto top;
default:
putchar(*p);
}
}
Can someone explain why it enters an infinite loop instead of stopping when *p is NULL? I had in mind the following: when *p is 0x20 or \n go to the beginning of the loop again, since it tests the condition and evaluates the expression p++. So, I don’t see a reason for it to loop infinitely, or I really don’t get how the goto statement and labels work in the C programming language.
When you
goto top,p++is not executed, because the for loop is started again from the beginning. Then yougoto topagain. And then again. And then again. And forever.If you want your increment to work, use
continueinstead ofgoto. Or, better yet, do something even clearer:Oh, and by the way, avoid
gotostatements like the plague. Unless you’re generating C code in an automated way and it’s not supposed to be human readable,gotois virtually never a good idea.