Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ goto Statement

C++ goto Statement

C++ Loops C++ Loops

goto statement allows unconditional transfer of control to a labeled statement within the same function.

**Note:** In any programming language, the use of the goto statement is discouraged. Because it makes the program's control flow hard to track, and the program hard to understand and modify. Any program using the goto statement can be rewritten without needing the goto statement.

Syntax

The syntax of the **goto ** statement in C++:



goto label;

..

.

label: statement;

Here,label is the identifier that recognizes the labeled statement, and can be any plain text except C++ keywords. A labeled statement can be any statement, placed after the identifier and a colon (:).

Flowchart

Example

Example

#include

using

namespace

std

;

 

int

main

(

)

{

   

// local variable declaration

   

int

a

=

10

;

   

// do loop execution

   LOOP

:

do

   

{

       

if

(

a

==

15

)

       

{

         

// Skip iteration

          a

=

a

1

;

         

goto

LOOP

;

       

}

       

cout

<<

"Value of a: "

<<

a

<<

endl

;

       a

=

a

1

;

   

}

while

(

a

<

20

)

;

 

   

return

0

;

}

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



a 的值: 10

a 的值: 11

a 的值: 12

a 的值: 13

a 的值: 14

a 的值: 16

a 的值: 17

a 的值: 18

a 的值: 19

A good use of the goto statement is to exit deeply nested routines. For example, please see the code snippet below:



for(...) {

   for(...) {

      while(...) {

         if(...) goto stop;

         .

         .

         .

      }

   }

}

stop:

cout << "Error in program.\n";

Eliminating goto would cause some extra tests to be executed. A simple break statement would not work here, because it would only cause the program to exit the innermost loop.

C++ Loops C++ Loops