0
0
C++programming~5 mins

Jump statement overview in C++

Choose your learning style9 modes available
Introduction

Jump statements help you change the flow of your program quickly. They let you skip parts or repeat actions easily.

To stop a loop early when a condition is met.
To skip the rest of a loop and start the next round.
To exit a function and return a value immediately.
To jump to a specific part of code in rare cases.
To break out of nested loops or switch cases.
Syntax
C++
break;
continue;
return expression;
goto label;

label:
  // code here

break stops the nearest loop or switch.

continue skips to the next loop iteration.

return exits a function and optionally sends back a value.

goto jumps to a labeled statement (use carefully).

Examples
Stops the loop when i is 3, so it prints 0 1 2.
C++
for (int i = 0; i < 5; i++) {
  if (i == 3) break;
  std::cout << i << " ";
}
Skips printing 2, so output is 0 1 3 4.
C++
for (int i = 0; i < 5; i++) {
  if (i == 2) continue;
  std::cout << i << " ";
}
Returns the sum and exits the function immediately.
C++
int add(int a, int b) {
  return a + b;
}
Jumps over the assignment, so x stays 0.
C++
int x = 0;
goto skip;
x = 5;
skip:
std::cout << x;
Sample Program

This program loops from 0 to 4. It skips printing when i is 1, and stops the loop when i is 3.

C++
#include <iostream>

int main() {
  for (int i = 0; i < 5; i++) {
    if (i == 3) {
      std::cout << "Breaking at " << i << "\n";
      break;
    }
    if (i == 1) {
      std::cout << "Skipping " << i << "\n";
      continue;
    }
    std::cout << "Number: " << i << "\n";
  }
  return 0;
}
OutputSuccess
Important Notes

Use break and continue only inside loops or switch statements.

return ends the current function immediately.

goto can make code hard to read; use it only when necessary.

Summary

Jump statements control program flow by skipping or stopping parts.

break exits loops or switches early.

continue skips to the next loop cycle.

return exits a function and optionally sends back a value.

goto jumps to a labeled spot in code (use carefully).