C++ Goto
C++ goto Statement
A goto statement is used to jump the flow of a sequence of program execution. It transfers the control to some other part of the program. The goto uses an identifier that encountered the control of program jumps to an identifier.
Syntax
goto label; ... label: statement; ...

Example
This program calculates the average of numbers entered by the user. If the user enters a negative number, it ignores the number and calculates the average of the number entered before it.
# include <iostream> using namespace std; int main() { float num, average, sum = 0.0; int i, n; cout << "Maximum number of inputs: "; cin >> n; for(i = 1; i <= n; i++) { cout << "Enter n" << i << ": "; cin >> num; if(num < 0.0) { // Control of the program move to jump: goto label; } sum += num; } label: average = sum / (i - 1); cout << "\nAverage = " << average; return 0; }
Output:
Maximum number of inputs: 4 Enter n1: 4 Enter n2: 2 Enter n3: -3 Average = 3