Jack
Jack

Reputation: 16724

Why does the following code go into an infinite loop?

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.

Upvotes: 0

Views: 249

Answers (3)

Adeel Ahmed
Adeel Ahmed

Reputation: 1601

const char *s = "a   b    c  d !";
const char *p = s;

top:
for(; *p; p++) {
    switch(*p) {
    case 0x20: 
    case '\n': 
        p ++;
        goto top;
    default: 
        putchar(*p);
    }
}

You have to use p ++; before goto top;, because going to top: means you are restarting the loop.

Upvotes: 0

Nikos C.
Nikos C.

Reputation: 51842

When you goto top, p++ is not executed, because the for loop is started again from the beginning. Then you goto top again. And then again. And then again. And forever.

If you want your increment to work, use continue instead of goto. Or, better yet, do something even clearer:

for(p = s; *p != '\0'; p++) {
    switch(*p) {
    case 0x20:
    case '\n':
        // Do nothing.
        break;

    default: 
        putchar(*p);
    }
}

Oh, and by the way, avoid goto statements like the plague. Unless you're generating C code in an automated way and it's not supposed to be human readable, goto is virtually never a good idea.

Upvotes: 5

Murtuza Kabul
Murtuza Kabul

Reputation: 6514

do this

const char *s = "a   b    c  d !";
const char *p = s;

 for(; *p; p++) {
    switch(*p) {
    case 0x20: case '\n': continue;
    default: putchar(*p);
    }
  }

The reason is, your code is not completing even a single iteration and hence the p++ never comes to execution. When you continue instead of using label, it counts to one complete iteration.

Upvotes: 1

Related Questions