User Tools

Site Tools


c_sharp_continue

C Sharp C# continue

C# continue Keyword - Apply the continue keyword in a loop to end the current loop iteration.

  • Continue. “This statement alters control flow. It is used in loop bodies. It allows you to skip the execution of the rest of the iteration.”
  • An example. This program uses the continue statement. In a while-true loop, the loop continues infinitely. We call Sleep() to make the program easier to watch as it executes.

While

Sleep

Part 1 We increment the number “value” which starts at 0, and is incremented on its first iteration (so 0 is never printed).

Part 2 If the number is equal to 3, the rest of the iteration is terminated. Control moves to the next iteration.

C# program that uses continue keyword

using System;

using System.Threading;

class Program {

   static void Main()
   {
       int value = 0;
       while (true)
       {
           // Part 1: increment number.
           value++;
           // Part 2: if number is 3, skip the rest of this loop iteration.
           if (value == 3)
           {
               continue;
           }
           Console.WriteLine(value);
           // pause.
           Thread.Sleep(100);
       }
   }
} 1 2 4 5…

No enclosing loop. We must use a continue statement within a loop. We get an error from the compiler if no enclosing loop is found. The same restriction applies to break.

Break

C# program that causes continue error

class Program {

   static void Main()
   {
       continue;
   }
}

Error CS0139

  • No enclosing loop out of which to break or continue
  • Some notes. The C# language is a high-level language. When it is compiled, it is flattened into a sequence of instructions. These are intermediate language opcodes (IL)
  • And When we specify a continue in a loop, branch statements (which jump to other instructions) are generated.
  • Some notes, branches. In branch statements, a condition is tested. And based on whether the condition is true, the C# runtime jumps to another instruction in the sequence.
  • Offset - This new location is indicated by an offset in the opcode. So all branches “jump” to other parts of an instruction stream.
  • Note - The continue statement could be implemented by branching to the top of the loop construct if the result of the expression is true.

True, False

  • A summary. The continue statement exits a single iteration of a loop. It does not terminate the enclosing loop entirely or leave the enclosing function body.

Fair Use Source: https://www.dotnetperls.com/continue

c_sharp_continue.txt · Last modified: 2024/04/28 03:23 (external edit)