break

Terminate execution of for or while loop

Syntax

Description

example

breakterminates the execution of afororwhileloop. Statements in the loop after thebreakstatement do not execute.

In nested loops,breakexits only from the loop in which it occurs. Control passes to the statement that follows theendof that loop.

Examples

collapse all

Sum a sequence of random numbers until the next random number is greater than an upper limit. Then, exit the loop using abreakstatement.

limit = 0.8; s = 0;while1 tmp = rand;iftmp > limitbreakends = s + tmp;end

Tips

  • Thebreakstatement exits afororwhileloop completely. To skip the rest of the instructions in the loop and begin the next iteration, use acontinuestatement.

  • breakis not defined outside afororwhileloop. To exit a function, usereturn.

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Introduced before R2006a