Namespaces
Variants
Views
Actions

goto statement

From cppreference.com
< cpp‎ | language
Revision as of 22:13, 2 November 2012 by P12bot (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements
Jump statements
goto statement
return statement
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Initialization
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

Transfers control to a new location.

Used when it is otherwise impossible to transfer control to the desired location using conventional constructs.

Contents

Syntax

goto Template:sparam

Explanation

The goto statement transfers control to the location specified by Template:sparam. The goto statement must be in the same function as the Template:sparam it is referring. If goto statement transfers control backwards, all objects that are not yet initialized at the Template:sparam are destructed. It is illegal to transfer control forwards if doing so would skip initialization of an object.

Keywords

goto

Example

#include <iostream>
 
struct Object {
    ~Object() { std::cout << "d"; }
};
 
int main()
{
    int a = 10;
 
    //loop using goto
label:
    Object obj;
    std::cout << a << " ";
    a = a - 2;
 
    if (a != 0) {
        goto label;  //causes obj to be destructed
    }
    std::cout << '\n';
 
    //get out of multi-level loop easily
    for (int x = 0; x < 3; x++) {
        for (int y = 0; y < 3; y++) {
            std::cout << "(" << x << ";" << y << ") " << '\n';
            if (x + y >= 3) {
                goto endloop;
            }
        }
    }
endloop:
    std::cout << '\n';
 
    return 0;  //causes obj to be destructed
}

Output:

10 d8 d6 d4 d2
(0;0) (0;1) (0;2) (1;0) (1;1) (1;2)
d