I l @ ve RuBoard |
All the sample programs in this book were coded without using a single goto . In actual practice I find I use a goto statement about once every other year. For those rare times that a goto is necessary, its syntax is: goto label ; where label is a statement label. Statement labels follow the same naming convention as variable names . Labeling a statement is done as follows : label : statement ; For example: for (x = 0; x < X_LIMIT; ++x) { for (y = 0; y < Y_LIMIT; ++y) { assert((x >= 0) && (x < X_LIMIT)); assert((y >= 0) && (y < Y_LIMIT)); if (data[x][y] == 0) goto found; } } std::cout << "Not found\n"; exit(8); found: std::cout << "Found at (" << x << ',' << y << ")\n"; One of the things you don't want to do is to use a goto statement to skip over initialization code. For example: { goto skip_start; { int first = 1; skip_start: printf("First is %d\n", first); } } This confuses the compiler and should be avoided. Question 29-1: Why does Example 29-1 not print an error message when an incorrect command is entered? Hint: There is a reason I put this in the goto section. Example 29-1. def/def.cpp#include <iostream> #include <cstdlib> int main( ) { char line[10]; while (true) { std::cout << "Enter add(a), delete(d), quit(q): "; std::cin.getline(line, sizeof(line)); switch (line[0]) { case 'a': std::cout << "Add\n"; break; case 'd': std::cout << "Delete\n"; break; case 'q': std::cout << "Quit\n"; exit(0); defualt: std::cout << "Error:Bad command " << line[0] << '\n'; break; } } return (0); } |
I l @ ve RuBoard |