2

I am currently coding in C and using switch & getch, like this :

c=getch(); 
switch(c)
        {
            case 17: 
            //something
            break;

            case 19: 
            //something else
            break;

            default: //loop to get the right "case"
            break;

        }

However, I want to loop my switch in the case of we get into the "default". Does anything exist for that ? Or should I make a "while (x!=10)" -for example- looping my whole switch, and if I go into default, x==10??

Thanks a lot in advance !

Acajou
  • 21
  • 1
  • 2

4 Answers4

6

If you find goto distasteful, you can create a dummy loop and use continue after default: to force next loop iteration:

do {
  c = getch();
  switch(c) {
    case 17: 
      //something
      break;
    // ...
    default:
      continue;
  }
} while (false);
user4815162342
  • 141,790
  • 18
  • 296
  • 355
3

You can use do-while loop,. For example

int done;

do
{
    done = 1;

    c =getch(); 
    switch( c )
    {
        case 17: 
        //something
        break;

        case 19: 
            //something else
            break;

        default: //loop to get the right "case"
            done = 0;
            break;
    }
} while ( !done );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Though it is discouraged by most of the programmers to use goto, because of hampering to keep track of the flow of the program, you can use it. The statements are syntactically valid.

#include <stdio.h>
#include <conio.h>

int main()
{
    char c;
xx:
    c=getch();
    switch(c)
    {
    case 17:
        //something
        break;

    case 19:
        //something else
        break;

    default: //loop to get the right "case"
        goto xx;
        break;

    }

    return 0;
}
Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56
  • 2
    goto is evil, especially as `do{}while()` would be a) as effective and b) more readable. – nonchip Nov 29 '15 at 17:21
  • @nonchip sure, as OP mentioned about the while loop, I thought he could do it with loop and answer with loop would come straightforward. I also mentioned that it is discouraged, but it is good to know about `goto` in case of emergency. – Enamul Hassan Nov 29 '15 at 17:25
1

For best coding practices, just forget that the goto exists.

The following code does what you want

int  done = 0; // indicate not done
while( !done )
{
    done = 1; // indicate done
    //c=getch();  not portable, do not use
    c = getchar();

    switch(c)
    {
        case 17:
        //something
        break;

        case 19:
        //something else
        break;

        default: //loop to get the right "case"
            done = 0;  // oops, not done, so stay in loop
        break;
    } // end switch
} // end while
user3629249
  • 16,402
  • 1
  • 16
  • 17