The goto statement alters the normal sequence of execution in a C/C++ program; it is similar to an unconditional jump.
The label is an identifier. When the goto
statement is encountered, control of the program jumps to label:
, and the code starts executing after it.
The following example uses the goto
statement in a function that checks whether or not a number is a multiple of :
#include <iostream>using namespace std;// function to check even or notvoid multipleOfThree(int num){if (num % 3 == 0)goto multiple;elsegoto notMultiple;multiple:cout << num << " is a multiple of 3." << endl;return; // return if evennotMultiple:cout << num << " is not a multiple of 3." << endl;}// Driver codeint main(){int num1 = 18;multipleOfThree(num1);int num2 = 19;multipleOfThree(num2);}
While the
goto
statement appears to be very useful, its use is discouraged because, more often than not, it makes the program logic complex, difficult to follow, and creates complications when modifying the code. Therefore, one must be very cautious when using thegoto
statement.
Free Resources