Misplaced continue in switch case : C Programming



Misplaced continue in switch case

Consider below program, In the below program we wrote the continue statement inside the switch case statement.

Misplaced continue in switch case Examples

Example 1 : continue statement in switch

void main()
{
 int choice = 2 ;
 switch(choice)
 {
  case 1 :
        printf("In Case 1");
        break;

  case 2 :
        printf("In Case 2");
        continue;
		
  case 3 :
        printf("In Case 3");
        break;
 }
}

Output :

Error : misplaced continue

Explanation

In the above program we have written switch case statement. break statement in switch case is used to terminate the execution of the case. It takes control outside switch statement.

case 1 :
    printf("In Case 1");
    break;

When case 1 is executed then immediately after the execution of the case 1, break statement will move control out of switch block

case 2 :
    printf("In Case 2");
    continue;

Using continue statement in switch case will throw an error because continue statement takes control to the condition checking statement again

Example 2 : continue statement in if block

int main()
{
	
int num=10;

if(num == 10)
  continue;

return 0;
}

Output :

In function 'main':
Line 7: error: continue statement not within a loop

Important rule while using continue statement is that, We can use continue statement only within the loops. Switch case is conditional block not a loop so we cannot execute the continue statement inside switch

Lookup table :

Consider the below table in which we have mentioned whether continue/break statement is allowed in control and loop statements or not.

Misplaced continue in switch case C Programming