简体   繁体   English

您可以在C中的switch语句的案例中使用while循环吗?

[英]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? 在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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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