goto statement in C++ with example
The goto statement in C++ is used for transferring the control of a program to a given label. The syntax of goto statement looks like this:
goto label_name;
Program structure:
label1: ... ... goto label2; ... .. label2: ...
In a program we have any number of goto and label statements, the goto statement is followed by a label name, whenever goto statement is encountered, the control of the program jumps to the label specified in the goto statement.
The goto statements are almost never used in any development as they are complex and makes your program much less readable and more error prone. In place of goto, you can use continue and break statement.
Example of goto statement:
#include <iostream> using namespace std; int main(){ int num; cout<<"Enter a number: "; cin>>num; if (num % 2==0){ goto print; } else { cout<<"Odd Number"; } print: cout<<"Even Number"; return 0; }
Output:
Enter a number: 42
Even Number
Related Posts:
- Data Types in C++
- Operators in C++
- Recursion in C++ with example
- Functions in C++ with example
- Break statement in C++ with example
- Continue Statement in C++ with example
- do-while loop in C++ with example
- While loop in C++ with example
- For loop in C++ with example
- Switch Case statement in C++ with example
- If else Statement in C++
- Constructors in C++
- Enumeration in C++
- OOPs Concepts in C++
- this pointer in C++
- Pointers in C++
- Strings in C++
- Passing Array to Function in C++
- Multidimensional Arrays in C++
- Arrays in C++
- Difference between Function Overloading and Function overriding in C++
- Function Overriding in C++ with examples
- Function overloading in C++ with examples
- Polymorphism in C++ and its types
- Inheritance in C++ with examples
- Destructors in C++ with examples
- Encapsulation in C++ with example
- Friend Class and Friend Functions in C++
- Interfaces in C++ with Examples
- Abstraction in C++ with example