如何从交换机内部跳出循环?

发布于 2024-08-05 11:07:12 字数 337 浏览 14 评论 0原文

我正在编写一些如下所示的代码:

while(true) {
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        break; // **HERE, I want to break out of the loop itself**
    }
}

有没有直接的方法可以做到这一点?

我知道我可以使用一个标志,并通过在开关后面放置一个条件中断来中断循环。我只是想知道 C++ 是否已经有一些构造。

I'm writing some code that looks like this:

while(true) {
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        break; // **HERE, I want to break out of the loop itself**
    }
}

Is there any direct way to do that?

I know I can use a flag, and break from the loop by putting a conditional break just after the switch. I just want to know if C++ has some construct for this already.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

自由范儿 2024-08-12 11:07:12

您可以使用goto

while ( ... ) {
   switch( ... ) {
     case ...:
         goto exit_loop;

   }
}
exit_loop: ;

You can use goto.

while ( ... ) {
   switch( ... ) {
     case ...:
         goto exit_loop;

   }
}
exit_loop: ;
花伊自在美 2024-08-12 11:07:12

另一种解决方案是将关键字 continuebreak 结合使用,即:

for (;;) {
    switch(msg->state) {
        case MSGTYPE:
            // code
            continue; // continue with loop
        case DONE:
            break;
    }
    break;
}

使用 continue 语句完成您想要的每个 case 标签。循环继续并使用 break 语句完成应终止循环的 case 标签。

当然,只有当 switch 语句之后没有额外的代码要执行时,此解决方案才有效。

An alternate solution is to use the keyword continue in combination with break, i.e.:

for (;;) {
    switch(msg->state) {
        case MSGTYPE:
            // code
            continue; // continue with loop
        case DONE:
            break;
    }
    break;
}

Use the continue statement to finish each case label where you want the loop to continue and use the break statement to finish case labels that should terminate the loop.

Of course this solution only works if there is no additional code to execute after the switch statement.

酸甜透明夹心 2024-08-12 11:07:12

前提

无论语言或所需的功能如何,以下代码都应被视为不良形式:

while( true ) {
}

支持参数

while( true ) 循环是不良形式,因为它:

  • 破坏了 while 循环的隐含契约。
    • while 循环声明应明确声明退出条件。
  • 意味着它会永远循环。
    • 必须阅读循环内的代码才能理解终止子句。
    • 永远重复的循环会阻止用户从程序内部终止程序。
  • 效率低下。
    • 有多个循环终止条件,包括检查“true”。
  • 容易出现错误。
    • 无法轻松确定将每次迭代始终执行的代码放置在何处。
  • 导致不必要的复杂代码。
  • 自动源代码分析。
    • 为了查找错误、程序复杂性分析、安全检查或在不执行代码的情况下自动派生任何其他源代码行为,指定初始中断条件允许算法确定有用的不变量,从而改进自动源代码分析指标。< /里>
  • 无限循环。
    • 如果每个人都对非无限循环使用 while(true) ,那么当循环实际上没有终止条件时,我们就失去了简洁通信的能力。 (可以说,这已经发生了,所以这一点毫无意义。)

“Go To”的替代方案

以下代码是更好的形式:

while( isValidState() ) {
  execute();
}

bool isValidState() {
  return msg->state != DONE;
}

优点

无标志。没有转到。也不例外。易于改变。易于阅读。易于修复。另外,代码:

  1. 将循环工作负载的信息与循环本身隔离开来。
  2. 允许维护代码的人轻松扩展功能。
  3. 允许在一处分配多个终止条件。
  4. 将终止子句与要执行的代码分开。
  5. 对于核电站来说更安全。 ;-)

第二点很重要。在不知道代码如何工作的情况下,如果有人要求我让主循环让其他线程(或进程)拥有一些 CPU 时间,我会想到两种解决方案:

选项#1

轻松插入暂停:

while( isValidState() ) {
  execute();
  sleep();
}

选项#2

覆盖执行:

void execute() {
  super->execute();
  sleep();
}

此代码比带有嵌入式开关的循环更简单(因此更容易阅读)。 isValidState 方法应仅确定循环是否应继续。该方法的主力应抽象为 execute 方法,该方法允许子类覆盖默认行为(使用嵌入式 switchgoto 是一项艰巨的任务代码>)。

Python 示例

对比 StackOverflow 上发布的以下答案(与 Python 问题):

  1. 永远循环。
  2. 要求用户输入他们的选择。
  3. 如果用户的输入是“重新启动”,则继续永远循环。
  4. 否则,永远停止循环。
  5. 结尾。

Code

while True: 
    choice = raw_input('What do you want? ')

    if choice == 'restart':
        continue
    else:
        break

print 'Break!' 

Versus:

  1. 初始化用户的选择。
  2. 当用户选择“重新启动”一词时循环。
  3. 要求用户输入他们的选择。
  4. 结尾。

Code

choice = 'restart';

while choice == 'restart': 
    choice = raw_input('What do you want? ')

print 'Break!'

在这里,while True 会产生误导性且过于复杂的代码。

Premise

The following code should be considered bad form, regardless of language or desired functionality:

while( true ) {
}

Supporting Arguments

The while( true ) loop is poor form because it:

  • Breaks the implied contract of a while loop.
    • The while loop declaration should explicitly state the only exit condition.
  • Implies that it loops forever.
    • Code within the loop must be read to understand the terminating clause.
    • Loops that repeat forever prevent the user from terminating the program from within the program.
  • Is inefficient.
    • There are multiple loop termination conditions, including checking for "true".
  • Is prone to bugs.
    • Cannot easily determine where to put code that will always execute for each iteration.
  • Leads to unnecessarily complex code.
  • Automatic source code analysis.
    • To find bugs, program complexity analysis, security checks, or automatically derive any other source code behaviour without code execution, specifying the initial breaking condition(s) allows algorithms to determine useful invariants, thereby improving automatic source code analysis metrics.
  • Infinite loops.
    • If everyone always uses while(true) for loops that are not infinite, we lose the ability to concisely communicate when loops actually have no terminating condition. (Arguably, this has already happened, so the point is moot.)

Alternative to "Go To"

The following code is better form:

while( isValidState() ) {
  execute();
}

bool isValidState() {
  return msg->state != DONE;
}

Advantages

No flag. No goto. No exception. Easy to change. Easy to read. Easy to fix. Additionally the code:

  1. Isolates the knowledge of the loop's workload from the loop itself.
  2. Allows someone maintaining the code to easily extend the functionality.
  3. Allows multiple terminating conditions to be assigned in one place.
  4. Separates the terminating clause from the code to execute.
  5. Is safer for Nuclear Power plants. ;-)

The second point is important. Without knowing how the code works, if someone asked me to make the main loop let other threads (or processes) have some CPU time, two solutions come to mind:

Option #1

Readily insert the pause:

while( isValidState() ) {
  execute();
  sleep();
}

Option #2

Override execute:

void execute() {
  super->execute();
  sleep();
}

This code is simpler (thus easier to read) than a loop with an embedded switch. The isValidState method should only determine if the loop should continue. The workhorse of the method should be abstracted into the execute method, which allows subclasses to override the default behaviour (a difficult task using an embedded switch and goto).

Python Example

Contrast the following answer (to a Python question) that was posted on StackOverflow:

  1. Loop forever.
  2. Ask the user to input their choice.
  3. If the user's input is 'restart', continue looping forever.
  4. Otherwise, stop looping forever.
  5. End.

Code

while True: 
    choice = raw_input('What do you want? ')

    if choice == 'restart':
        continue
    else:
        break

print 'Break!' 

Versus:

  1. Initialize the user's choice.
  2. Loop while the user's choice is the word 'restart'.
  3. Ask the user to input their choice.
  4. End.

Code

choice = 'restart';

while choice == 'restart': 
    choice = raw_input('What do you want? ')

print 'Break!'

Here, while True results in misleading and overly complex code.

季末如歌 2024-08-12 11:07:12

一个巧妙的方法是将其放入一个函数中:

int yourfunc() {

    while(true) {

        switch(msg->state) {
        case MSGTYPE: // ... 
            break;
        // ... more stuff ...
        case DONE:
            return; 
        }

    }
}

可选(但“不好的做法”):正如已经建议的,您可以使用 goto,或者在开关内抛出异常。

A neatish way to do this would be to put this into a function:

int yourfunc() {

    while(true) {

        switch(msg->state) {
        case MSGTYPE: // ... 
            break;
        // ... more stuff ...
        case DONE:
            return; 
        }

    }
}

Optionally (but 'bad practices'): as already suggested you could use a goto, or throw an exception inside the switch.

浅唱ヾ落雨殇 2024-08-12 11:07:12

AFAIK 在 C++ 中没有“双重中断”或类似的构造。最接近的是 goto - 虽然它的名字有不好的含义,但它在语言中的存在是有原因的 - 只要小心谨慎地使用它,它就是一个可行的选择。

AFAIK there is no "double break" or similar construct in C++. The closest would be a goto - which, while it has a bad connotation to its name, exists in the language for a reason - as long as it's used carefully and sparingly, it's a viable option.

倾城泪 2024-08-12 11:07:12

您可以将开关放入一个单独的函数中,如下所示:

bool myswitchfunction()
{
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        return false; // **HERE, I want to break out of the loop itself**
    }
    return true;
}

while(myswitchfunction())
    ;

You could put your switch into a separate function like this:

bool myswitchfunction()
{
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        return false; // **HERE, I want to break out of the loop itself**
    }
    return true;
}

while(myswitchfunction())
    ;
冰葑 2024-08-12 11:07:12

即使您不喜欢 goto,也不要使用异常来退出循环。以下示例显示了它可能有多丑陋:

try {
  while ( ... ) {
    switch( ... ) {
      case ...:
        throw 777; // I'm afraid of goto
     }
  }
}
catch ( int )
{
}

我将使用 goto ,如 这个答案。在这种情况下,goto 将使代码比任何其他选项更清晰。我希望这个问题会有帮助。

但我认为使用 goto 是这里唯一的选择,因为字符串 while(true)。您应该考虑重构您的循环。我想采用以下解决方案:

bool end_loop = false;
while ( !end_loop ) {
    switch( msg->state ) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        end_loop = true; break;
    }
}

或者甚至是以下解决方案:

while ( msg->state != DONE ) {
    switch( msg->state ) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
}

Even if you don't like goto, do not use an exception to exit a loop. The following sample shows how ugly it could be:

try {
  while ( ... ) {
    switch( ... ) {
      case ...:
        throw 777; // I'm afraid of goto
     }
  }
}
catch ( int )
{
}

I would use goto as in this answer. In this case goto will make code more clear then any other option. I hope that this question will be helpful.

But I think that using goto is the only option here because of the string while(true). You should consider refactoring of your loop. I'd suppose the following solution:

bool end_loop = false;
while ( !end_loop ) {
    switch( msg->state ) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        end_loop = true; break;
    }
}

Or even the following:

while ( msg->state != DONE ) {
    switch( msg->state ) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
}
携君以终年 2024-08-12 11:07:12

在这种情况下,没有用于跳出循环的 C++ 构造。

使用标志来中断循环或(如果适用)将代码提取到函数中并使用return

There's no C++ construct for breaking out of the loop in this case.

Either use a flag to interrupt the loop or (if appropriate) extract your code into a function and use return.

清风疏影 2024-08-12 11:07:12

不,C++ 没有这方面的构造,因为关键字“break”已经被保留用于退出 switch 块。或者,带有退出标志的 do..while() 就足够了。

do { 
    switch(option){
        case 1: ..; break;
        ...
        case n: .. ;break;
        default: flag = false; break;
    }
} while(flag);

No, C++ does not have a construct for this, given that the keyword "break" is already reserved for exiting the switch block. Alternatively a do..while() with an exit flag could suffice.

do { 
    switch(option){
        case 1: ..; break;
        ...
        case n: .. ;break;
        default: flag = false; break;
    }
} while(flag);
暮倦 2024-08-12 11:07:12

您可能会使用 goto,但我更愿意设置一个停止循环的标志。然后断开开关。

You could potentially use goto, but I would prefer to set a flag that stops the loop. Then break out of the switch.

好久不见√ 2024-08-12 11:07:12

为什么不直接修复 while 循环中的条件,从而使问题消失呢?

while(msg->state != DONE)
{
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        // We can't get here, but for completeness we list it.
        break; // **HERE, I want to break out of the loop itself**
    }
}

Why not just fix the condition in your while loop, causing the problem to disappear?

while(msg->state != DONE)
{
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        // We can't get here, but for completeness we list it.
        break; // **HERE, I want to break out of the loop itself**
    }
}
离不开的别离 2024-08-12 11:07:12

考虑到解释的深度,这让我感到惊讶......这就是你需要的一切......

bool imLoopin = true;

while(imLoopin) {

    switch(msg->state) {

        case MSGTYPE: // ... 
            break;

        // ... more stuff ...

        case DONE:
            imLoopin = false;
            break;

    }

}

哈哈!真的吗!这就是您所需要的!一个额外的变量!

It amazes me how simple this is considering the depth of explanations... Here's all you need...

bool imLoopin = true;

while(imLoopin) {

    switch(msg->state) {

        case MSGTYPE: // ... 
            break;

        // ... more stuff ...

        case DONE:
            imLoopin = false;
            break;

    }

}

LOL!! Really! That's all you need! One extra variable!

扭转时空 2024-08-12 11:07:12

我认为;

while(msg->state != mExit) 
{
    switch(msg->state) 
    {
      case MSGTYPE: // ...
         break;
      case DONE:
      //  .. 
      //  ..
      msg->state =mExit;
      break;
    }
}
if (msg->state ==mExit)
     msg->state =DONE;

I think;

while(msg->state != mExit) 
{
    switch(msg->state) 
    {
      case MSGTYPE: // ...
         break;
      case DONE:
      //  .. 
      //  ..
      msg->state =mExit;
      break;
    }
}
if (msg->state ==mExit)
     msg->state =DONE;
几味少女 2024-08-12 11:07:12

我遇到了同样的问题并使用标志解决了。

bool flag = false;
while(true) {
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        flag = true; // **HERE, I want to break out of the loop itself**
    }
    if(flag) break;
}

I got same problem and solved using a flag.

bool flag = false;
while(true) {
    switch(msg->state) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        flag = true; // **HERE, I want to break out of the loop itself**
    }
    if(flag) break;
}
不…忘初心 2024-08-12 11:07:12

因为 switch 使用 breakswitch 中退出(而不是从 while(1) 中退出),它需要 goto 语句:

while(1) {
    switch (*p) {
      case ' ':
        p++;
        break;
      case '\n':
        p++; *s=p; return(i);
      case '\0':
        *s=p; return(i);
      default:
        token[i]=p;
        i++;
        p++;
        goto ex1;
    };
  };
  ex1:

我无法将多个 case 添加到同一行,例如:

case ' ','\t':

它将是

case ' ': case '\t':

这就是原因也许这里使用的中断...

看起来最常见的情况应该放在列表的顶部,以使程序运行得更快。
它可能没有并行执行来搜索不同的案例。

标准 c 可能缺少一些有关此切换的方法:
https://blog.hackajob.co /better-c-switch-statements-for-a-range-of-values/
=>允许您在 switch 表达式中使用 <、>、<= 和 >= 运算符

我认为它应该是(如果 c 语言语法更改)如下:

switch (c) {
  case >= 5:
     ... op1
  endcase;
  case == 1:
  case == 3:
     ... op2
  endcase;
  default:
    ...
};

当 c 等于时执行 op2 1或3并且当c大于或等于5时op1被执行。
因为以类似的方式很容易进行等于或大于/小于的比较。

  while(1) {
    switch (c) {
      case >= 2:
         ... op1
      case <= 5:
         ... op2
      break;
      default:
        ...
    };
  };

这种情况下,op1 是在 c 大于 2 的情况下执行的,op2 是在 2<=c<=5 的情况下执行的,并且 break 从 while 循环中退出。

Because the switch uses the break to break out from the switch (not from the while(1)), it needs the goto-statement:

while(1) {
    switch (*p) {
      case ' ':
        p++;
        break;
      case '\n':
        p++; *s=p; return(i);
      case '\0':
        *s=p; return(i);
      default:
        token[i]=p;
        i++;
        p++;
        goto ex1;
    };
  };
  ex1:

I can't add multiple case to same line like:

case ' ','\t':

it would be

case ' ': case '\t':

That's why maybe the break used here...

It looks the most frequent cases should be placed at the top of the list to make the program run faster.
It may not have parallel execution for searching the different cases.

It is possible that the standard c then has missing some methods about this switching:
https://blog.hackajob.co/better-c-switch-statements-for-a-range-of-values/
=> allows you to use the <, >, <=, and >= operators in a switch expression

I was thinking that it should be (if c-language syntax changed) like:

switch (c) {
  case >= 5:
     ... op1
  endcase;
  case == 1:
  case == 3:
     ... op2
  endcase;
  default:
    ...
};

where op2 is executed when c is equal to 1 or 3 and when c is larger than or equal to 5 op1 is executed.
Because comparison for equal or larger/smaller than would occur easily in similar manner.

  while(1) {
    switch (c) {
      case >= 2:
         ... op1
      case <= 5:
         ... op2
      break;
      default:
        ...
    };
  };

this case op1 is executed for c larger than 2 and op2 executed for 2<=c<=5 and break exits it from while-loop.

一页 2024-08-12 11:07:12

最简单的方法是在执行 SWITCH 之前放置一个简单的 IF ,然后 IF 测试退出循环的条件.......尽可能简单

The simplest way to do it is to put a simple IF before you do the SWITCH , and that IF test your condition for exiting the loop .......... as simple as it can be

叶落知秋 2024-08-12 11:07:12

C++ 中的 break 关键字仅终止最嵌套的封闭迭代或 switch 语句。因此,您无法直接在 switch 语句中跳出 while (true) 循环;但是您可以使用以下代码,我认为这是解决此类问题的绝佳模式:

for (; msg->state != DONE; msg = next_message()) {
    switch (msg->state) {
    case MSGTYPE:
        //...
        break;

    //...
    }
}

如果您需要在 msg->state 等于 DONE 时执行某些操作(例如运行清理例程),然后将该代码立即放置在 for 循环之后;即如果您当前有:

while (true) {
    switch (msg->state) {
    case MSGTYPE:
        //... 
        break;

    //...

    case DONE:
        do_cleanup();
        break;
    }

    if (msg->state == DONE)
        break;

    msg = next_message();
}

则使用:

for (; msg->state != DONE; msg = next_message()) {
    switch (msg->state) {
    case MSGTYPE:
        //...
        break;

    //...
    }
}

assert(msg->state == DONE);
do_cleanup();

The break keyword in C++ only terminates the most-nested enclosing iteration or switch statement. Thus, you couldn't break out of the while (true) loop directly within the switch statement; however you could use the following code, which I think is an excellent pattern for this type of problem:

for (; msg->state != DONE; msg = next_message()) {
    switch (msg->state) {
    case MSGTYPE:
        //...
        break;

    //...
    }
}

If you needed to do something when msg->state equals DONE (such as run a cleanup routine), then place that code immediately after the for loop; i.e. if you currently have:

while (true) {
    switch (msg->state) {
    case MSGTYPE:
        //... 
        break;

    //...

    case DONE:
        do_cleanup();
        break;
    }

    if (msg->state == DONE)
        break;

    msg = next_message();
}

Then use instead:

for (; msg->state != DONE; msg = next_message()) {
    switch (msg->state) {
    case MSGTYPE:
        //...
        break;

    //...
    }
}

assert(msg->state == DONE);
do_cleanup();
南薇 2024-08-12 11:07:12
while(MyCondition) {
switch(msg->state) {
case MSGTYPE: // ... 
    break;
// ... more stuff ...
case DONE:
   MyCondition=false; // just add this code and you will be out of loop.
    break; // **HERE, you want to break out of the loop itself**
}
}
while(MyCondition) {
switch(msg->state) {
case MSGTYPE: // ... 
    break;
// ... more stuff ...
case DONE:
   MyCondition=false; // just add this code and you will be out of loop.
    break; // **HERE, you want to break out of the loop itself**
}
}
謌踐踏愛綪 2024-08-12 11:07:12

好吧,这是一个疯狂、不守规矩的本土 cpp 程序员和另一位程序员。优雅的程序员不愿意在循环体内使用终止条件,但我非常不同意。我用循环比普通程序员更多的事实来证明我的信念,因为我手动进行文本解析,而不是使用正则表达式。再加上我需要循环的其他情况。所以我理解循环内终止条件的需要。事实上,即使我只有一个条件,我可能更喜欢 while(true) 循环;为了在循环体内执行我的所有代码。例如:

while(true)
{
    if(condition)
    {
     // do something
     return;
    }

    // .... long body
}

这种格式允许人们立即看到循环终止时采取了什么操作。

无论如何,我将解释一下 BREAK_OUT_OF 关键字。它允许您从内部循环或 switch 语句中跳出外部循环或 switch 语句。该关键字设置为在 cpp 的下一版本(cpp 2026)中出现。但不用担心,现在您可以在原始 cpp 编译器中模拟它。以下是步骤。

步骤1:使用以下命令下载BREAK_OUT_OF关键字包:

#define BREAK_OUT_OF(ID) goto STATEMENT##ID
#define S_ID(ID)
#define DEF_S_ID(ID) STATEMENT##ID:

不要被命令中的goto语句所迷惑。这不是我们都讨厌的常规 goto 语句。它是变相的 jmp 语句。

第二步:现在你已经下载了兼容包;当您需要从内部语句中跳出外部语句时;你首先给它一个ID。您可以使用 S_ID 关键字来执行此操作。

while(true) S_ID(first_loop)

步骤 3:将 DEF_S_ID 关键字紧接在语句主体之后。请注意,在即将到来的 cpp 26 中,这将自动为我们完成。

while(true) S_ID(first_loop)
{
}DEF_S_ID(first_loop)

最后一步:使用 BREAK_OUT_OF 关键字从内循环中跳出外循环

while(true) S_ID(first_loop)
{
    switch(10) S_ID(1)
    {
     case 10: BREAK_OUT_OF(first_loop);
     case 0: BREAK_OUT_OF(1);
    }DEF_S_ID(1)
}DEF_S_ID(first_loop)

Well its the crazy unruly homegrown cpp programmer with another one. The classy programmers have cringed against using terminating conditions inside loop body but I highly disagree. I qualify my belief with the fact that I used loops much more than the regular programmer, since I do text parsing manually and not with regex. Plus other kinds of situtations where I needed loops. So I understand the need for terminating conditions inside loops. Infact, even if I only have one condition, I may prefer a while(true) loop; in order to do all my code inside the loop body. eg:

while(true)
{
    if(condition)
    {
     // do something
     return;
    }

    // .... long body
}

This format allows persons to see what action is taken on loop termination immediately.

Anyhow, I will explain the BREAK_OUT_OF keyword. It allows you to break out of outer loops or switch statements, from within an inner loop or switch statement. This keyword is set to come in the next version of cpp, cpp 2026. But dont worry, for now you can emulate it in your primitive cpp compilers. Here are the steps.

Step 1: Download the BREAK_OUT_OF keyword package with the following command:

#define BREAK_OUT_OF(ID) goto STATEMENT##ID
#define S_ID(ID)
#define DEF_S_ID(ID) STATEMENT##ID:

Dont be fooled by the goto statement in the commands. Its not a regular goto statement that we all hate. Its a jmp statement in disguise.

Step 2: Now that you downloaded the compatibility package; when you need to break out of an outer statement from within an inner statement; you first give it an ID. You do this using S_ID keyword.

while(true) S_ID(first_loop)

Step 3: Place DEF_S_ID keyword immediately after statement body. Note that in the up coming cpp 26, This will automatically be done for us.

while(true) S_ID(first_loop)
{
}DEF_S_ID(first_loop)

Last Step: break out of outer loop from within inner loop using BREAK_OUT_OF keyword

while(true) S_ID(first_loop)
{
    switch(10) S_ID(1)
    {
     case 10: BREAK_OUT_OF(first_loop);
     case 0: BREAK_OUT_OF(1);
    }DEF_S_ID(1)
}DEF_S_ID(first_loop)
终陌 2024-08-12 11:07:12

如果我记得很好的 C++ 语法,您可以向 break 语句添加一个标签,就像 goto 一样。所以你想要的很容易写成:

while(true) {
    switch(msg->state) {
    case MSGTYPE: // ...
        break;
    // ... more stuff ...
    case DONE:
        break outofloop; // **HERE, I want to break out of the loop itself**
    }
}

outofloop:
// rest of your code here

If I remember C++ syntax well, you can add a label to break statements, just like for goto. So what you want would be easily written:

while(true) {
    switch(msg->state) {
    case MSGTYPE: // ...
        break;
    // ... more stuff ...
    case DONE:
        break outofloop; // **HERE, I want to break out of the loop itself**
    }
}

outofloop:
// rest of your code here
岁月静好 2024-08-12 11:07:12
  while(true)
  {
    switch(x)
    {
     case 1:
     {
      break;
     }
    break;
   case 2:
    //some code here
   break;
  default:
  //some code here
  }
}
  while(true)
  {
    switch(x)
    {
     case 1:
     {
      break;
     }
    break;
   case 2:
    //some code here
   break;
  default:
  //some code here
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文