C# loop-break vs. continue


En un bucle de C# (siéntase libre de responder para otros lenguajes), ¿cuál es la diferencia entre romper y continuar como un medio para abandonar la estructura del bucle y pasar a la siguiente iteración?

Ejemplo:

foreach (DataRow row in myTable.Rows)
{
    if (someConditionEvalsToTrue)
    {
        break; //what's the difference between this and continue ?
        //continue;
    }
}
Author: callisto, 2008-08-09

15 answers

break saldrá del bucle completamente, continue simplemente saltará la iteración actual.

Por ejemplo:

for (int i = 0; i < 10; i++) {
    if (i == 0) {
        break;
    }

    DoSomeThingWith(i);
}

La ruptura hará que el bucle salga en la primera iteración - DoSomeThingWith nunca se ejecutará. Esto aquí:

for (int i = 0; i < 10; i++) {
    if(i == 0) {
        continue;
    }

    DoSomeThingWith(i);
}

No ejecutará DoSomeThingWith para i = 0, pero el bucle continuará y DoSomeThingWith se ejecutará para i = 1 hasta i = 9.

 1327
Author: Michael Stum,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-08 17:21:23

Una manera muy fácil de entender esto es colocar la palabra "bucle" después de cada una de las palabras clave. Los términos ahora tienen sentido si se leen como frases cotidianas.

break loop - bucle se rompe y se detiene.

continue loop-loop continúa ejecutándose con la siguiente iteración.

 366
Author: JeremiahClark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-04 18:27:22

Break hace que el contador de programa salte fuera del alcance del bucle más interno

for(i = 0; i < 10; i++)
{
    if(i == 2)
        break;
}

Funciona así

for(i = 0; i < 10; i++)
{
    if(i == 2)
        goto BREAK;
}
BREAK:;

Continue salta hasta el final del bucle. En un bucle for, continue salta a la expresión increment.

for(i = 0; i < 10; i++)
{
    if(i == 2)
        continue;

    printf("%d", i);
}

Funciona así

for(i = 0; i < 10; i++)
{
    if(i == 2)
        goto CONTINUE;

    printf("%d", i);

    CONTINUE:;
}
 92
Author: SemiColon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-08-19 20:21:17

break detendría el bucle foreach completamente, continue saltaría al siguiente DataRow.

 24
Author: palmsey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-04 18:28:05

Hay más de unas pocas personas a las que no les gusta break y continue. La última queja que vi sobre ellos fue en JavaScript: The Good Parts por Douglas Crockford. Pero encuentro que a veces usar uno de ellos realmente simplifica las cosas, especialmente si tu lenguaje no incluye un estilo de bucle do-while o do-until.

Tiendo a usar break en bucles que buscan algo en una lista. Una vez encontrado, no tiene sentido continuar, por lo que también podría dejar de fumar.

Uso continue cuando se hace algo con la mayoría de los elementos de una lista, pero todavía quiere saltar unos pocos.

La declaración break también es útil cuando se solicita una respuesta válida de alguien o algo. En lugar de:

Ask a question
While the answer is invalid:
    Ask the question

Podría eliminar alguna duplicación y usar:

While True:
    Ask a question
    If the answer is valid:
        break

El bucle do-until que mencioné antes es la solución más elegante para ese problema en particular:

Do:
    Ask a question
    Until the answer is valid

No hay duplicación, y tampoco se necesita break.

 18
Author: yukondude,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-08-08 22:35:46

Todos han dado una muy buena explicación. Todavía estoy publicando mi respuesta solo para dar un ejemplo si eso puede ayudar.

// break statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        break; // It will force to come out from the loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Aquí está la salida:

0 [Impreso] 1 [Impreso] 2 [Impreso]

Así que 3 [Impreso] & 4 [Impreso] no se mostrará como hay ruptura cuando i = = 3

//continue statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        continue; // It will take the control to start point of loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Aquí está la salida:

0 [Impreso] 1[Impreso] 2[Impreso] 4[Impreso]

Así que 3 [Impreso] no se mostrará ya que hay continuar cuando i = = 3

 12
Author: Pritom Nandy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-28 13:41:50

Siempre me confundía si debía usar break o continuar. Esto es lo que me ayuda a recordar:

¿Cuándo usar break vs continue?

  1. Break - es como romper. Es triste, ustedes se están separando.

Romper

  1. Continue - significa que vas a dar hoy un descanso y ordenar todo mañana (es decir, omitir la iteración actual)!

Continuar

 9
Author: BKSpurgeon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-10 11:18:42

Break

Break fuerza a un bucle a salir inmediatamente.

Continuar

Esto hace lo contrario de break. En lugar de terminar el bucle, inmediatamente loops de nuevo, omitiendo el resto del código.

 7
Author: Sona,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-28 06:58:57

Por ejemplo

foreach(var i in Enumerable.Range(1,3))
{
    Console.WriteLine(i);
}

Imprime 1, 2, 3 (en líneas separadas).

Añadir una condición de rotura en i = 2

foreach(var i in Enumerable.Range(1,3))
{
    if (i == 2)
        break;

    Console.WriteLine(i);
}

Ahora el bucle imprime 1 y se detiene.

Reemplace el descanso con un continuar.

foreach(var i in Enumerable.Range(1,3))
{
    if (i == 2)
        continue;

    Console.WriteLine(i);
}

Ahora el bucle imprime 1 y 3 (omitiendo 2).

Así, break detiene el bucle, mientras que continue salta a la siguiente iteración.

 6
Author: Colonel Panic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-07 18:04:54

Ruby desafortunadamente es un poco diferente. PD: Mi memoria es un poco borrosa en esto, así que disculpas si me equivoco

En lugar de break / continue, tiene break / next, que se comportan igual en términos de bucles

Los bucles (como todo lo demás) son expresiones, y "devuelven" lo último que hicieron. La mayoría de las veces, obtener el valor devuelto de un bucle no tiene sentido, por lo que todo el mundo hace esto

a = 5
while a < 10
    a + 1
end

Sin embargo, puede hacer esto

a = 5
b = while a < 10
    a + 1
end # b is now 10

SIN EMBARGO, una gran cantidad de código ruby 'emula' un bucle usando un bloque. El ejemplo canónico es

10.times do |x|
    puts x
end

Como es mucho más común que la gente quiera hacer cosas con el resultado de un bloqueo, aquí es donde se complica. break / next significa diferentes cosas en el contexto de un bloque.

Break saltará del código que llamó al bloque

A continuación se saltará el resto del código en el bloque, y 'devolver' lo que especifique a la persona que llama del bloque. Esto no tiene ningún sentido sin ejemplos.

def timesten
    10.times{ |t| puts yield t }
end


timesten do |x|
   x * 2
end
# will print
2
4
6
8 ... and so on


timesten do |x|
    break
    x * 2
end
# won't print anything. The break jumps out of the timesten function entirely, and the call to `puts` inside it gets skipped

timesten do |x|
    break 5
    x * 2
end
# This is the same as above. it's "returning" 5, but nobody is catching it. If you did a = timesten... then a would get assigned to 5

timesten do |x|
    next 5
    x * 2
end 
# this would print
5
5
5 ... and so on, because 'next 5' skips the 'x * 2' and 'returns' 5.

Así que sí. Ruby es impresionante, pero tiene algunos casos de esquina horribles. Este es el segundo peor que he visto en mis años de usarlo :-)

 5
Author: Orion Edwards,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-08-09 02:31:13

Respuesta simple:

Break sale del bucle inmediatamente.
Continue comienza a procesar el siguiente elemento. (Si hay alguno, saltando a la línea de evaluación del for/while)

 5
Author: Maltrap,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-22 09:11:16

Por favor, permítanme decir lo obvio: tenga en cuenta que agregar ni break ni continue, reanudará su programa; es decir, atrapé un cierto error, luego de registrarlo, quise reanudar el procesamiento, y hubo más tareas de código entre la siguiente fila, así que simplemente lo dejé caer.

 5
Author: David Hall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-14 11:59:41

Para romper completamente un bucle foreach, se usa break ;

Para ir a la siguiente iteración en el bucle, se usa continue;

Break es útil si está recorriendo una colección de objetos (como Filas en una Datatable) y está buscando una coincidencia en particular, cuando encuentre esa coincidencia, no hay necesidad de continuar a través de las filas restantes, por lo que desea romper.

Continue es útil cuando has logrado lo que necesidad en lado una iteración del lazo. Que normalmente tienen continuar después de un si.

 3
Author: Gopesh Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-09 12:50:42

Si no desea usar break simplemente aumente el valor de I de tal manera que haga que la condición de iteración sea falsa y el bucle no se ejecute en la siguiente iteración.

for(int i = 0; i < list.Count; i++){
   if(i == 5)
    i = list.Count;  //it will make "i<list.Count" false and loop will exit
}
 2
Author: Umair Khalid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-03 06:18:55

En cuanto a otros idiomas:

'VB
For i=0 To 10
   If i=5 then Exit For '= break in C#;
   'Do Something for i<5
next

For i=0 To 10
   If i=5 then Continue For '= continue in C#
   'Do Something for i<>5...
Next
 0
Author: dba,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-20 14:25:35