Understanding and Application of C ++ goto statements

Source: Internet
Author: User

Reposted from Sina Blog:

1: Why not use the GOTO statement?

Source (from Wikipedia ):

Goto is a statement that can be found in many computer programming languages. It is an English word.GoAndTo. When executing this statement, it transfers the control process to another statement unconditionally (also called "jump "). The jump statement must specify the mark. in different languages, the mark can be an identifier or a line number. At the machine code level,GotoIs a form of branch.

In some languagesGotoKeyword to implement the same function, suchBreakOrContinueA keyword can follow an identifier. The snobol language supports the suffix of a statement. You can perform an unconditional jump after the statement is executed.

Goto statements are supported by most advanced languages. Only a few advanced languages do not support goto statements. For example,GotoIs a reserved word in Java, but cannot be used. For example, Pascal does not have a Goto, but procedure can be used to execute one plus syntax.

The GOTO statement has always been the target of criticism and debate. The main negative impact is the use of the GOTO statement to make the program more readable and even become an "noodle code" that cannot be maintained ". As structured programming became increasingly popular from 1960s to 1970s, many computer scientists have come to the conclusion that programs should always use commands called "structured" control procedures, such as loops and if-then-else statements to replace Goto. Even today, many Program-style encoding standards do not allow the use of goto statements. The defender of the GOTO statement believes that using the GOTO statement with restrictions does not cause low-quality code, and claims that in many programming languages, some tasks cannot be directly implemented without using one or more goto statements. Such as the implementation of finite state automation, jumping out of nested loops, and exception handling.

Probably the most famous criticism of goto is that edsger wybe Dijkstra, in an article in 1968, was called the harmful theory of goto statements.
To statement considered harmful. [2] dijela believes that the use of goto statements without restrictions should be abolished from advanced languages because it makes the tasks of analyzing and verifying Program correctness (especially involving loops) complex. Another point of view is thatStructured
Programming with go to statements
 [3], the article analyzes many common programming tasks and finds that some of them use goto to obtain the optimal structure.

These criticisms have been effective in the design of some programming languages. Although Ada Language designers realized criticism of goto in the late 1970s S, this statement was still included, mainly used to support Automatic GenerationGotoThe code that is essential to the statement. [4] However, labels that serve as the destination of a GOTO statement must be enclosed in parentheses (for example:<Start_again>), And this syntax is not used in other languages. This makes it easy to check the existence of a goto destination in the program. The GOTO statement itself uses a simple formGotoStart_again;.


Cause: the GOTO statement makes the static and dynamic structures of the program inconsistent, making it hard for the program to understand and locate errors.
Some people think that the GOTO statement is flexible to use, and in some cases it can improve the efficiency of the program.
In 1974, D. E. knus made a comprehensive and fair comment on the GOTO statement debate. The basic idea is to use the GOTO statement without restrictions, especially the GOTO statement that jumps back, this will make the program structure difficult to understand. In this case, avoid using the GOTO statement as much as possible. However, in other cases, it is also necessary to use some goto statements with control in order to improve program efficiency and avoid damaging the program's good structure. In his words, "in some cases, I suggest deleting the GOTO statement; in other cases, I suggest introducing the GOTO statement ."
Later, G. gkappini and C. pomm theoretically proved that any program can be expressed in a sequence, branch, or repetitive structure. This conclusion shows that removing the GOTO statement from the advanced programming language does not affect the programming capability of the advanced programming language, and the program structure is clearer.
GOTO statement results: The Goto statements are reserved in C/C ++ and other advanced programming languages, but are recommended to be used less or less. In some updated advanced programming languages, such as Java, which does not provide a GOTO statement, although it specifies a goto as a keyword, it does not support its use, making the program concise and easy to read; even so, later C # still supports the GOTO statement. One advantage of the GOTO statement is that it can ensure that the program has a unique exit, avoiding the too large if nesting.
Goto can be considered: 1. Jump out of multiple loops; 2. Clear resources when an error occurs; 3. Increase the definition of the program.
Unrestricted use of Goto: destroys the clear program structure, making the program readable worse, and even becomes an "noodle code" that cannot be maintained ". Errors or risks often occur. For example, it may skip the construction of some objects, initialization of variables, and important computing statements.
The proposal of the GOTO statement directly promotes the idea of structured programming and the birth and development of programming methodology. The Structured Programming Method introduces engineering ideas and structural ideas, which greatly improves the development and programming of large-scale software. The main principles of the structured program design method can be summarized as top-down, progressive refinement, modularization, and restrictions on the use of goto statements.
The following principles about the use of the GOTO statement can be used for your reference. 1) The GOTO statement can only be used in the same function, but not from one function to another. 2) When a GOTO statement is used in the same function, the start point of goto should be the end of a small function in the function, the target label of goto should start with another small function in the function. 3) It is not allowed to jump from a complex execution state location goto another location. For example, jumping out from multiple nested loops is not allowed. 4) Avoid redirection in two directions. This will most easily lead to "noodle code ".

2: enthusiastic answers from netizens

Goto is not unusable. The key is that the tag to which the Goto points must be behind the Goto line.
It is wrong to disable goto blindly.
See geraldönberger "Understanding professional programmers"

If you want to develop software, especially for the team, it is best not to use goto for future project maintenance and easy-to-understand code;
Goto will affect Compiler optimization, and 9-to-9 goto can be converted to a goto-less method.

If the GOTO statement is followed by an endless loop!
If the GOTO statement is in the front, it will easily lead to an endless loop !!!
Also, Goto Statement can be replaced by repeat or while!
Therefore, you generally do not need to go !!

Because it will disrupt the programming structure order.

3:

Front:

Goto statements are notorious in C/C ++, and some books (or company programming specifications) have suggested disabling goto statements. The result is that when some programmers see the GOTO statement being used in a program, they instinctively think that the program is "junk ". In addition, some programmers feel that they are not professional because they use the GOTO statement. In fact, everything cannot be too radical. The use of goto statements can greatly simplify the program and improve the readability and maintainability of the program. Before starting to illustrate its benefits, we should first use some statistical data to show that the GOTO statement has not been abandoned due to the "Notorious" nature. These statistics may not be accurate but convincing. For the operating system, the Linux-2.6.21 kernel uses 20,333 goto statements, the VxWorks-6.2 uses 9142, And the last 941 goto statements are applied to the rtems-4.9.2; and, the glibc-2.9 library uses 1750 goto statements. All these statistics show that the key to disabling the Goto language is not as terrible as you think.
-- Use it properly.

Reprinted from: http://blog.sina.com.cn/s/blog_6908039c0101f5hx.html

 

Reposted from the csdn blog:

Goto can only jump to the function body, but not to the function in vitro. That is, Goto has a local scope and needs to be in the same stack.

You need to add a label at the start point of the program segment to jump. Part2 in the following example.

1. The GOTO statement can be used to jump out of a deep nested loop.

[CPP]
View plaincopyprint?
  1. # Include <iostream>
  2. Using namespace STD;
  3. Int main ()
  4. {
  5. For (INT I = 0; I <10; I ++)
  6. For (Int J = 0; j <10; j ++)
  7. For (int K = 0; k <10; k ++)
  8. {
  9. Cout <I * j * k <"";
  10. If (216 = I * j * K)
  11. Goto Part2; // The break cannot skip multiple cycles.
  12. }
  13. Cout <"omitted here" <Endl;
  14. Part2:
  15. Cout <"Part2" <Endl;
  16. System ("pause ");
  17. }
# Include <iostream> using namespace STD; int main () {for (INT I = 0; I <10; I ++) for (Int J = 0; j <10; j ++) for (int K = 0; k <10; k ++) {cout <I * j * k <""; if (216 = I * j * k) goto Part2; // The break cannot skip multiple cycles} cout <"omitted here" <Endl; Part2: cout <"Part2" <Endl; System ("pause ");}

2. The GOTO statement can jump back or forward.

[CPP]
View plaincopyprint?
  1. # Include <iostream>
  2. Using namespace STD;
  3. Int main ()
  4. {
  5. Int X, sum = 0;
  6. // Defines the L1.
  7. L1: cout <"x = ";
  8. Cin> X;
  9. If (x =-1)
  10. Goto L2; // when the user inputs-1, it is transferred to the L2 statement.
  11. Else
  12. Sum + = X;
  13. Goto L1; // if the user does not enter-1, it is transferred to the L1 statement. The program keeps accumulating user input to the sum variable.
  14. // Defines the L2 number.
  15. L2: cout <"sum =" <sum <Endl; // once switched to L2, the accumulated result is output and the program running ends.
  16. System ("pause ");
  17. }
# Include <iostream> using namespace STD; int main () {int X, sum = 0; // defines the label l1l1: cout <"x ="; CIN> X; if (x =-1) goto L2; // when the user inputs-1, go to the L2 statement else sum + = x; goto L1; // if the user does not enter-1, it is transferred to the L1 statement, and the program accumulates the user input to the sum variable silently. // Define the label l2l2: cout <"sum =" <sum <Endl; // once switched to L2, the accumulative result is output and the program running ends. System ("pause ");}

3. You can also jump out of the switch or jump between cases.

For example:

[CPP]
View plaincopyprint?
  1. # Include <iostream>
  2. Using namespace STD;
  3. Int main ()
  4. {
  5. Char;
  6. L1:
  7. Cout <"enter a character" <Endl;
  8. Cin>;
  9. Switch ()
  10. {
  11. Case 'A ':
  12. Cout <"case a" <Endl;
  13. Goto L1;
  14. // Break;
  15. L2:
  16. Case 'B ':
  17. Cout <"case B" <Endl;
  18. Break;
  19. Case 'C ':
  20. Cout <"Case C" <Endl;
  21. // Break;
  22. Goto L2;
  23. Default:
  24. Break;
  25. }
  26. System ("pause ");
  27. }
# Include <iostream> using namespace STD; int main () {char a; L1: cout <"enter a character" <Endl; CIN>; switch (a) {Case 'A': cout <"case a" <Endl; goto L1; // break; L2: Case 'B ': cout <"case B" <Endl; break; Case 'C': cout <"Case C" <Endl; // break; goto L2; default: break;} system ("pause ");}

Reprinted from: http://blog.csdn.net/generalhking/article/details/8011306

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.