Break

From Game Editor

Revision as of 18:44, 25 November 2009 by Asmodeus (Talk | contribs)
(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)
Jump to: navigation, search

The break statement is used to exit from a loop (do, while, for) or switch statement.

Example:

char letter_to_guess = 'a';
char guess;
int max_guesses = 3;
for ( num_guesses = 0; num_guesses < max_guesses; ++ num_guesses)
{
  printf("Guess my letter, a thru z, in %d guesses.\n", max_guesses - num_guesses);
  scanf("%c", &guess);
  if (guess == letter_to_guess)
  {
    printf("You guessed it in %d guesses!\n", num_guesses);
    break;
  }
}
print("Done.\n");

The break only exits the inner-most loop or switch statement.

Example:

char letter_to_guess = 'a';
char guess, choice;
int max_guesses = 3;
do
{
  for ( num_guesses = 0; num_guesses < max_guesses; ++ num_guesses)
  {
    printf("Guess my letter, a thru z, in %d guesses.\n", max_guesses - num_guesses);
    scanf("%c", &guess);
    if (guess == letter_to_guess)
    {
      printf("You guessed it in %d guesses!\n", num_guesses);
      break;
    }
  }
  print("Press 'q' to quit, any other key to play again.\n");
  scanf("%c", &choice);
}
while ( choice != 'q');

If the guess is correct, only the for loop surrounding the break is ended. The outer do loop continues to execute.