×

goto statement in C and C++

goto statement in C and C++

The goto statement is a jump statement, also sometimes referred to as an unconditional jump statement. Within a function, the goto statement can be used to jump from anywhere in general conditions.

NOTE ? the use of goto statements in any programming language is strongly discouraged because it makes it difficult to track a program's control flow, making it very difficult to understand the program and difficult to modify. 

Syntax:

Syntax1      |   Syntax2
----------------------------
goto label_name;
..
..
..
label_name: C-statements

The first line in the syntax above tells the compiler to go, or jump to, the statement marked as a label. The label here is a user-defined identifier indicating the target declaration. The statement followed immediately after 'label:' is the state of destination. In the above syntax, the 'label:' may also appear before the 'goto label;' statement.

goto statement in C and C++

Example:

1. We shall see a similar situation in this case to the one shown above in Syntax1. Assume we have to write a program where we have to check whether there is a number even or not and use the goto statement to print consequently.The program below explains how:

// C++ program to check if a number is
// even or not using goto statement
#include <iostream>
using namespace std;
// function to check even or not
void checkEvenOrNot(int num)
{
    if (num % 2 == 0)
    // jump to even
        goto even; 
    else
    // jump to odd
        goto odd; 
even:
    cout << num << " is even";
    // return if even
    return; 
odd:
    cout << num << " is odd";
}
// Driver program to test above function
int main()
{
    int num = 35;
    checkEvenOrNot(num);
    return 0;
}

Output:

goto statement in C and C++

Example in C:-

// C program to check if a number is
// even or not using goto statement
#include <stdio.h>
// function to check even or not
void checkEvenOrNot(int num)
{
    if (num % 2 == 0)
        // jump to even
        goto even; 
    else
        // jump to odd
        goto odd; 
even:
    printf("%d is even", num);
    // return if even
    return; 
odd:
    printf("%d is odd", num);
}
int main() {
    int num = 35;
    checkEvenOrNot(num);
    return 0;
}

Output:

goto statement in C and C++

2. In this case, we can see a similar situation to the one seen in Syntax1 above. Suppose we have to write a program using the goto statement, which prints numbers from 1 to 10. The program below explains how to do so.

// C++ program to print numbers
// from 1 to 10 using goto statement
#include <iostream>
using namespace std;
// function to print numbers from 1 to 10
void printNumbers()
{
    int s = 5;
label:
    cout << s << " ";
    s++;
    if (s <= 20)
        goto label;
}
// Driver program to test above function
int main()
{
    printNumbers();
    return 0;
}

Output:

goto statement in C and C++

Example in C:

// C program to print numbers
// from 5 to 20 using goto statement
#include <stdio.h>
// function to print numbers from 5 to 20
void printNumbers()
{
    int s = 5;
label:
    printf("%d ",s);
    s++;
    if (s <= 20)
        goto label;
}
// Driver program to test above function
int main() {
    printNumbers();
    return 0;
}

Output:

goto statement in C and C++

Disadvantages of using goto Statement:

The use of the goto statement is highly disincentive as it makes the logic of the program very complex.

The use of goto makes it very difficult to evaluate and verify the correctness of the programs (especially those that require loops).

Using break and continue statements can simply avoid the use of goto.


Related Topics

Array of sets in C++

Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. A collection of data objects stored in a continuous way is...

6 minutes read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

C++ Writing to file

In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file. Syntax file-stream-class   file-stream-object;   file-stream-object.write((char *)&var , sizeof (var)); The write() takes two arguments. The first argument is the address of variable var...

2 minutes read.

Palindrome Using While Loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.

Leap Year Program in C++

What is a Leap Year? A solar year is the length of time that it takes for Earth to orbit the Sun - approximately 365.25 days. In a calendar year, we...

4 minutes read.

Difference between exit() and _Exit() in C++

Before understanding the difference between the exit() and _Exit(), one must know about exit() and _Exit() functions. The exit() function in C/C++ The exit() method in the C language kills the calling...

3 minutes read.

Floating Point Operations and Associativity in C, C++ and Java

In this tutorial, we are going to compare Floating-point operations and the concept of associativity. Before we apply the concept of associativity in the floating-point operations in all three programming...

3 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

C++ Close file

C++ File Handling close() Function A file which is opened while reading or writing in file handling must be closed after performing an action on it. The close() function is used to close...

2 minutes read.

C++ Global Variable

In C++, a global variable is a variable that is defined outside of any function or class and can be accessed by any function or class in the program. Global...

4 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

C++ Static

What is the Static keyword? In C++, the keyword static is used to give an element some particular properties. Static elements are only given storage in the static storage region once...

4 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

Array of Vectors in C++ STL

Prerequisites: C++ STL Arrays and C++ STL Vector. A group of items kept in consecutive memory region is known as an array. It is to group similar objects of the same...

4 minutes read.

C++ Dijkstra Algorithm Using the Priority Queue

In this article we will be finding the shortest routes from a source vertex in a graph to all vertices in the graph, given a graph and a source vertex...

5 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.