The break statement is used to alter the flow of control inside loops within any programming language. The break statement is normally used in looping constructs and is used to cause immediate termination of the innermost enclosing loop.
The Batch Script language does not have a direct ‘for’ statement which does a break but this can be implemented by using labels. The following diagram shows the diagrammatic explanation of the break statement implementation in Batch Script.
The key thing to note about the above implementation is the involvement of two ‘if’ conditions. The second ‘if’ condition is used to control when the break is implemented. If the second ‘if’ condition is evaluated to be true, then the code block is not executed and the counter is directly implemented.
Following is an example of how to carry out the implementation of the break statement.
@echo off SET /A "index=1" SET /A "count=5" :while if %index% leq %count% ( if %index%==2 goto :Increment echo The value of index is %index% :Increment SET /A "index=index + 1" goto :while )
The key thing to note about the above program is the addition of a label called :Increment. When the value of index reaches 2, we want to skip the statement which echoes its value to the command prompt and directly just increment the value of index.
The above command produces the following output.
The value of index is 1 The value of index is 3 The value of index is 4 The value of index is 5