HPlogo HP C/HP-UX Reference Manual: Version A.05.55.02 > Chapter 6 Statements

goto

» 

Technical documentation

Complete book in PDF

 » Table of Contents

 » Index

Syntax

goto label;

Arguments

label

This is a label or tag associated with an executable statement.

Description

The purpose of the goto statement is to enable program control to jump to some other statement. The destination statement is identified by a statement label, which is just a name followed by a colon. The label must be in the same function as the goto statement that references it.

Few programming statements have produced as much debate as the goto statement. The goto statement is necessary in more rudimentary programming languages, but its use in high-level languages is generally frowned upon. Nevertheless, most high-level languages, including C, contain a goto statement for those rare situations where it can't be avoided.

With deeply nested logic there are times when it is cleaner and simpler to bail out with one goto rather than backing out of the nested statements. The most common and accepted use for a goto is to handle an extraordinary error condition.

Example

The following example shows a goto that can easily be avoided by using the while loop, and also shows an illegal goto:

/* Program name is "goto_example". This program finds the
* circumference and area of a circle when the user gives
* the circle's radius.
*/
#include <stdio.h>
#define PI 3.14159

int main(void)
{
float cir, radius, area;
char answer;
extern void something_different(void);

circles:
printf("Enter the circle's radius: ");
scanf("%f", &radius);
cir = 2 * PI * radius;
area = PI * (radius * radius);
printf("The circle's circumference is: %6.3f\n", cir);
printf("Its area is: %6.3f\n", area);
printf("\nAgain? y or n: ");
fflush(stdin);
scanf("%c", &answer);

if (answer == 'y' || answer == 'Y')
goto circles;
else {
printf("Do you want to try something different? ");
fflush(stdin);
scanf("%c", &answer);
if (answer == 'y' || answer == 'Y')
/* goto different; WRONG! This label is in */
/* another block. */
something_different();
} /* end else */
}

void something_different(void)
{
different:
printf("Hello. This is something different.\n");
}

If you execute this program, you get the following output:

Enter the circle's radius: 3.5
The circle's circumference is: 21.991
Its area is: 38.484

Again? y or n: y
Enter the circle's radius: 6.1
The circle's circumference is: 38.327
Its area is: 116.899

Again? y or n: n
Do you want to try something different? y
Hello. This is something different.

© Hewlett-Packard Development Company, L.P.