English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn about the goto statement, how it works, and why it should be avoided.
In C ++In programming, the goto statement is used to change the normal order of program execution by transferring control to another part of the program.
goto label; ... .. ... ... .. ... ... .. ... label: statement; ... .. ...
In the above syntax, label is an identifier. When encountering goto label;, the program jumps to the label: and executes the code below it.
//This program calculates the average of the numbers entered by the user. //If the user enters a negative number, it will ignore the number and //Calculate the average of the numbers entered before. # include <iostream> using namespace std; int main() { float num, average, sum = 0.0; int i, n; cout << "Maximum input number: "; cin >> n; for(i = 1; i <= n; ++i) { cout << "Enter number n" << i << ": "; cin >> num; if(num < 0.0) { // Control the program to jump to jump goto jump; } sum += num; } jump: average = sum / (i - 1); cout << "\nAverage = " << average; return 0; }
Output Result
Maximum input number: 10 Enter number n1: 2.3 Enter number n2: 5.6 Enter number n3: -5.6 Average = 3.95
You can write any c++program, without the need to use goto statements, therefore not using goto statements is generally considered a good idea.
The goto statement can jump to any part of the program, but it can make the program's logic complex and chaotic.
In modern programming, the goto statement is considered a harmful construct and a bad programming habit.
In most C ++in a program, you can usebreak and continue Statementsinstead of goto Statements.