简体   繁体   中英

Can you use a while loop inside a case in switch statement in C?

This might be a really stupid question, and if it is, please excuse me for it, but I have been looking for an answer before and I haven't found anything. Is it possible to write something like

case 'i':
    do
    {
        root=insert(root,code[1]);
        scanf("%s",code);
    }while (code[0]=='i');
    break;

in C? Thank you for your answer and sorry again if this is a stupid question. Have a nice day :)

Yes you can, though for anything other than very short loops it can rapidly make your code unreadable.

In such cases it's better to put the loop into a function and call it from the case. That's short, succinct, and easily maintained.

Another I find worth doing is

switch (ch)
{
   case 'i':
   {
      // do stuff
      MainLoop();
      break;
   } 
}

Simply because it keeps the curly braces all neat and tidy though that's probably going to annoy a lot of people!

If it is necessary for your project, then you can use it. There is no harm in using it. Compiler wouldn't throw any error or warning. It will work as expected if created with care.

But it could make your code unreadable and also it will increase the level of indentation.

You can create a function which will have your loop. It could increase readability of the code.

For example,


case 'i':
        func();
        break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM