Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如果值为true,则退出两个for循环_C_Loops - Fatal编程技术网

C 如果值为true,则退出两个for循环

C 如果值为true,则退出两个for循环,c,loops,C,Loops,我将如何完成以下任务 for (x=0;x<3;x++) { for (y=0;y<3;y++) { if (z == 1) { // jump out of the two for loops } } } // go on to do other things for(x=0;x将z添加到最外层的条件表达式中,并中断最内层的循环 for(x = 0; x < 3 && z != 1;

我将如何完成以下任务

for (x=0;x<3;x++) {
    for (y=0;y<3;y++) {
        if (z == 1) {
            // jump out of the two for loops
        }
     }
}
// go on to do other things

for(x=0;x将
z
添加到最外层的条件表达式中,并中断最内层的循环

for(x = 0; x < 3 && z != 1; x++) {
    for(y = 0; y < 3; y++) {
        if(z == 1) {
            break;
        }
     }
 }
(x=0;x<3&&z!=1;x++)的
{
对于(y=0;y<3;y++){
如果(z==1){
打破
}
}
}

当然,这涉及到相当多的手工操作-在您提供的代码片段中,
z
没有更新。当然,如果此代码要工作,则必须如此。

假设您不需要
y
x
的值,只需为它们分配将使两个循环退出的值:

for (x=0;x<3;x++) 
{
    for (y=0;y<3;y++) 
    {
        if (z == 1) 
        {
           y = 3 ;
           x = 3 ;
        }
     }
}

for(x=0;x
for(x=0;xHave标志,并将其打破

int flag=0;

for(x = 0; x < 3; x++)  
{
   for(y = 0; y < 3; y++) 
   {
       if(z == 1)
       {
          flag=1;
          break;
       }
   }
   if(flag)
     break;
 }
int标志=0;
对于(x=0;x<3;x++)
{
对于(y=0;y<3;y++)
{
如果(z==1)
{
flag=1;
打破
}
}
国际单项体育联合会(旗)
打破
}

退出两个循环并避免任何可能跟随最内部循环的代码的好方法是将循环放入函数中并返回所需的任何值

for (x=0;x<3;x++) 
{
    for (y=0;y<3;y++) 
    {
        if (z == 1) 
        {
            return RETURN_VALUE
        }
        //avoids this code
    }
    //and this one too
}

用于(x=0;x可以使用goto或将其放在函数中并使用return。这是一种使用
goto
可能合适的情况。我想现在就使用goto。实际的代码有点凌乱,或者下面的任何一种解决方案都是上述问题的重复。不知怎么的,没有找到那个问题。投票关闭。假设是这样ual代码在内部loop@Leeor是的,在这种情况下应该更加小心。我实际上是在使用2 for循环遍历二维矩阵,所以这不会真的起作用。@codedude这是怎么回事:如果你不将
z
作为循环的自然终止?我没有看到复制粘贴错误,如果你标记优点是即使你的逻辑复杂,你也会中断。在条件块中添加所需的中断。如果在if条件之后有某个东西做了某件事,那么就需要复制粘贴错误(因为此时他想要中断)。假设我在for循环中有多个类似上面的if语句。如果第一个if语句为true并且返回了一些值,它会跳过下一个if语句吗?当函数返回值时,函数退出。
for (x=0;x<3;x++) 
{
    for (y=0;y<3;y++) 
    {
        if (z == 1) 
        {
            return RETURN_VALUE
        }
        //avoids this code
    }
    //and this one too
}