Home > Mobile >  Is it possible to use continue keyword outside a loop in C ?
Is it possible to use continue keyword outside a loop in C ?

Time:09-23

According to ISO C :

The continue statement shall occur only in an iteration-statement and causes control to pass to the loop-continuation portion of the smallest enclosing iteration-statement, that is, to the end of the loop. More precisely, in each of the statements

while (foo) {           do {                    for(;;){
  {                     {                       {
      // ...              //....                 //...
  }                     }                       }
  contin:;             contin:;                contin:;
  }                    } while (foo);           }

a continue not contained in an enclosed iteration statement is equivalent to goto contin

Based on the last part of the quote, I thought that the following would be allowed:

#include <iostream>
using namespace std;
int main() {
    continue;
    cout << "Will be jumped" << endl;
contin:
}

I thought this will work as a goto statement, jumping to contin. What did I miss?

CodePudding user response:

This is slight phrasing issue. What the quote means is that in

for (;;) {
  {
    // ...
  }
contin: ;
}

The ... can be anything, including another iteration statement.

for (;;) {
  {
    while(foo()) {
        // ...
        continue;
    }
  }
contin: ;
}

The continue; that is not nested inside another looping construct, is going to be equivalent to goto contin;. But if it is contained, it will of course continue the internal loop, not the outer one.

Bear in mind that contin: ; is used for exposition purposes. It doesn't mean there's a literal C -level label you can do things with.

  • Related