We can use goto statements (unconditional branch statements) to jump to a label in a program. In C++ and Pascal, a label is specified by an identifier (the name of the label) followed by a colon (:). However, labels in a Pascal program should be declared with the reserved word label, while labels in C++ programs need not be declared.
The following program makes use of an unconditional branch to draw an inverted triangle with asterisks (*). However, the number of rows is limited to 10 or less.
C++ version | Pascal version |
#include <iostream.h> main() { int i, j, n; cout << "n? "; cin >> n; for (i = 1; i <= n; i++) { if (i > 10) goto finished; for (j = n; j >= i; j--) cout << "* "; cout << endl; } finished: cout << "Finished!" << endl; return 0; } |
program prog_22(input, output); label finished; var i, j, n: integer; begin write('n? '); readln(n); for i := 1 to n do begin if i > 10 then goto finished; for j := n downto i do write('* '); writeln end; finished: writeln('Finished!') end. |
Sample output 1 (text in red is entered by user): | |
n? 8 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Finished! |
|
Sample output 2 (text in red is entered by user): | |
n? 15 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Finished! |
Although using unconditional branches is quite convenient, it is not preferable. In practice, it is almost always easy to write code without unconditional branches. For example, the shaded part of the above program can be written as follows:
C++ version | Pascal version |
#include <iostream.h> main() { int i, j, n; cout << "n? "; cin >> n; i = 1; while ((i <= n) && (i <= 10)) { for (j = n; j >= i; j--) cout << "* "; cout << endl; i++; } cout << "Finished!" << endl; return 0; } |
program prog_23(input, output); var i, j, n: integer; begin write('n? '); readln(n); i := 1; while (i <= n) and (i <= 10) do begin for j := n downto i do write('* '); writeln; i := i + 1 end; writeln('Finished!') end. |