Switch statement within while loop in C -


there several postings concerning switch statements within while loops, except fact none of them done in c, @ least i've seen. c++ can create boolean expressions, i'm aware of, not in c. have while loop contains switch control. however, when write break statements within switch, goes beginning of loop , makes program run forever. ignore functions use, work sure. need clarification on handling of nesting. thanks!

here main.c:  while(1) {     printf("0) exit\n1) list tasks\n2) add task\n");                                                 printf("3)delete task\n4) add task file\n");                                                printf("what do?\n");     fgets(buf1, 50, stdin);                                                                          p = atoi(buf1);     switch(p)     {           case 0:              break;           case 1:              printtasklist(ptasklist);             break;           case 2:             printf("enter task name: ");             fgets(buf2,100,stdin);             printf("enter task priority: ");             fgets(buf3,100,stdin);             printf("enter task start date: ");             fgets(buf4,50,stdin);             ptask = maketask(buf2,buf4,buf3);             addtasktoend(ptasklist,ptask);             break;           case 3:             printtasklist(ptasklist);             printf("what task delete? ");             fgets(buf6,50,stdin);             tasknum = atoi(buf6);             removetask(ptasklist,tasknum);             break;           case 4:             printf("enter filename ");             fgets(buf7,50,stdin);             break;           default:             printf("error: %d: incorrect menu option\n", p);      } } 

break; exit out of nearest enclosing switch or loop. jump 2 levels, you'll have use dreaded goto, or reorganize return accomplish desired semantics.

while(1) {     switch(x) {     case 0: goto endwhile;     } } endwhile: ; 

or

void loop() {     while(1) {         switch(x) {         case 0: return;         }     } } //... loop(); //... 

you can totally use boolean expression in c. use int.

int quit = 0; while(!quit) {     switch(x) {     case 0: quit = 1; break;     } } 

c has boolean data type, if want it.

#include <stdbool.h>  bool quit = false; while(!quit) {     switch(x) {     case 0: quit = true; break;     } } 

and 1 more option, totally insane.

#include <setjmp.h>  jmp_buf jbuf; if (!setjmp(jbuf))     while(1) {         switch(x) {         case 0: longjmp(jbuf, 1);         }     } 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -