Reputation: 21
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 !
Upvotes: 2
Views: 4528
Reputation: 154916
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);
Upvotes: 6
Reputation: 16540
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
Upvotes: 1
Reputation: 5445
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;
}
Upvotes: 1
Reputation: 310980
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 );
Upvotes: 3