C++ goto Statement

C++ goto Statement

In C++ programming, goto statement is used for altering the normal sequence of program execution by transferring control to some other part of the program.

Syntax of goto Statement

goto label;
... .. ...
... .. ...
... .. ...
label: 
statement;
... .. ...
In the syntax above, label is an identifier. When goto label; is encountered, the control of program jumps to label: and executes the code below it.
Working of goto statement in C++ programming

Example: goto Statement

  1. // This program calculates the average of numbers entered by user.
  2. // If user enters negative number, it ignores the number and
  3. // calculates the average of number entered before it.
  4. # include <iostream>
  5. using namespace std;
  6. int main()
  7. {
  8. float num, average, sum = 0.0;
  9. int i, n;
  10. cout << "Maximum number of inputs: ";
  11. cin >> n;
  12. for(i = 1; i <= n; ++i)
  13. {
  14. cout << "Enter n" << i << ": ";
  15. cin >> num;
  16. if(num < 0.0)
  17. {
  18. // Control of the program move to jump:
  19. goto jump;
  20. }
  21. sum += num;
  22. }
  23. jump:
  24. average = sum / (i - 1);
  25. cout << "\nAverage = " << average;
  26. return 0;
  27. }
Output
Maximum number of inputs: 10
Enter n1: 2.3
Enter n2: 5.6
Enter n3: -5.6

Average = 3.95
You can write any C++ program without the use of goto statement and is generally considered a good idea not to use them.

Reason to Avoid goto Statement

The goto statement gives power to jump to any part of program but, makes the logic of the program complex and tangled.
In modern programming, goto statement is considered a harmful construct and a bad programming practice.

Comments

Popular posts from this blog

C++ Templates ?

C++ Program to Print Number Entered by User

Educational Website