Break Statement

  • A break statement may appear inside a loop (while, do, or for) or a switch statement. It causes a jump out of these constructs, and hence terminates them. Like the continue statement, a break statement only applies to the loop or switch immediately enclosing it. It is an error to use the break statement outside a loop or a switch.
  • For example, suppose we wish to read in a user password, but would like to allow the user a limited number of attempts:
    for (i = 0; i < attempts; ++i)
    {
    cout << “Please enter your password: ”; 
    cin >> password;
    if (Verify(password)) 		//check password for correctness 
    break; 		//drop out of the loop
    cout << “Incorrect!\n”:
    }
    
  • Here we have assumed that there is a function called Verify which checks a password and returns true if it is correct and false otherwise. If the password entered is correct then loop will terminate break statement. Example


continue Statement << Previous

Next >> Functions

Our aim is to provide information to the knowledge seekers. 


comments powered by Disqus


Footer1