goto Statement in C++

About C goto statement:

 On this page we will discuss about the use of goto statement in C++.
The goto statement is a jump statement ,which is used to transfer the program control from one location to another location. It is also knows as unconditional jump statement and it can alter the normal flow of code.

goto statement in C++

What is C++ goto statement ?

In C language, the goto statement is used as unconditional jump statement which is used to jump from one statement to another statement at another location. By using the goto statement you can jump to above and below the current code flow.

Syntax

goto label;
... .. ...
... .. ...
label: 
statement;

Here, label cannot be the keyword. Basically label is an identifier. When goto  is encountered the flow of code is transferred from that statement to label and the statements below it gets executed.

Disadvantages of goto statement :

  • Since,goto statement is a unconditional statement,the efficiency of the program reduces by moving the control from one point to another unconditionally.
  • The goto statement can be use to move the control up or down which may lead to infinite loop.

Example :

 x:statement-1;
   statement-2;
   statement-3;
  goto x;
  • If we increase the number of goto statement in a program then the tracing become difficult.

Flowchart:

goto statement in c++ flowchart

Example:

Run
#include<iostream>
using namespace std;
int main ()
{
  int k = 12;
LOOP:do
    {
      if (k == 14)
	{
	  k = k + 1;
	  goto LOOP;      //goto statemet
	}
	
      printf ("value of k: %d\n", k);
      k++;

    }
  while (k < 25);

  return 0;
}

Output:

value of k: 12
value of k: 13
value of k: 15
value of k: 16
value of k: 17
value of k: 18
value of k: 19
value of k: 20
value of k: 21
value of k: 22
value of k: 23
value of k: 24

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription