Latest web development tutorials

C ++ goto statements

C ++ loop C ++ loop

goto statement allows the control unconditionally to a labeled statement within the same function.

Note: In any programming language, does not recommend the use of the goto statement.Because it makes it difficult to track the control flow of the program, making the program difficult to understand and difficult to modify. Any program that uses goto statements can be rewritten as the wording does not require the use of the goto statement.

grammar

Goto statement in C ++ syntax:

goto label;
..
.
label: statement;

Here, label is recognized identifier labeled statement can be anything other than C ++ keywords in plain text.Labeled statement can be any statement, placed in identifier and a colon (:) behind.

flow chart

C ++ goto statements

Examples

#include <iostream>
using namespace std;
 
int main ()
{
   // 局部变量声明
   int a = 10;

   // do 循环执行
   LOOP:do
   {
       if( a == 15)
       {
          // 跳过迭代
          a = a + 1;
          goto LOOP;
       }
       cout << "a 的值:" << a << endl;
       a = a + 1;
   }while( a < 20 );
 
   return 0;
}

When the above code is compiled and executed, it produces the following results:

a 的值: 10
a 的值: 11
a 的值: 12
a 的值: 13
a 的值: 14
a 的值: 16
a 的值: 17
a 的值: 18
a 的值: 19

goto statement is a good role is to exit deeply nested routine. For example, consider the following code fragment:

for(...) {
   for(...) {
      while(...) {
         if(...) goto stop;
         .
         .
         .
      }
   }
}
stop:
cout << "Error in program.\n";

Elimination ofgoto will lead to some additional tests are performed.A simplebreak statement here does not play a role, because it causes the program to exit the innermost loop.

C ++ loop C ++ loop