Skip to the content of the web site.

Lesson 210: The goto statement

Previous lesson Next lesson


Up until this point, you have seen three versions of flow-control:

  • function calls allowing you to perform the same operation over again possibly with different parameters,
  • conditional statements (if statements) allowing you to execute code only if a specific condition is satisfies, and
  • looping statements (while loops and for loops) allowing you to repeatedly execute the same code so long as some condition is satisfied.

There is one additional flow-control statement in C++: the goto statement. Any statement in a C++ function can be given an identifier as a label. While it looks odd:

double factorial( unsigned int n );

double factorial( unsigned int n ) {
	first: if ( n <= 1 ) {
		second: return 1.0;
	} else {
		third:  double result = 1.0;

		fourth: for ( unsgined int i = 1; i <= n; ++i ) {
			fifth: result *= i;
		}

		sixth: return result;
	}
}

Each label is an identifier. It is now possible to jump within a function to the label first: by using the statement goto first;. This causes the execution to continue executing that statement.

For example, the structured implementation of insertion sort, as we have seen it, uses a for-loop and a while-loop. This same program can be written with three goto statements:

template <typename T>
void insertion_sort_structured( T array[], size_t n );

template <typename T>
void insertion_sort_goto( T array[], size_t n );

template <typename T>
void insertion_sort_structured( T array[], size_t n ) {
	for ( size_t i = 1; i < n; ++i ) {
		T current = array[i];
		size_t j = i;

		while ( (j > 0) && (array[j - 1] > current) ) {
			array[j] = array[j - 1];
			--j;
		}

		array[j] = current;
	}
}

template <typename T>
void insertion_sort_goto( T array[], size_t n ) {
	size_t i{1};

	first: T current{array[i]};
	size_t j{i++};

	second: if ( array[j - 1] <= current ) {
		goto third;
	}

	array[j] = array[j - 1];

	if ( --j ) {
		goto second;
	}

	third: array[j] = current;

	if ( i != n ) {
		goto first;
	}
}

Using the goto statement can often be used to make code faster, but inevitably it resulted in code that was difficult to read: for example, the flow of the goto-implementation of the insertion sort causes one to think of spaghetti:

The use of the goto statement is highly discouraged, or outright banned as is the case of the JPL coding standard:

Rule 11 (simple control flow)
The goto statement shall not be used.

Further reading

Two papers you should consider reading include


Previous lesson Next lesson