How to use the “goto” in the C programming language?
In C language, you can use the goto statement to unconditionally jump to another position within the program. The syntax of the goto statement is as follows:
goto label;
In programming, a label is a tag composed of an identifier and a colon. Labels are typically used to mark a specific location in a program so that one can jump to that location when necessary.
Here is a simple example using the goto statement:
#include <stdio.h>
int main()
{
int i = 0;
label1:
printf("i = %d\n", i);
i++;
if (i < 5)
goto label1;
printf("End of program.\n");
return 0;
}
In the example above, label1 is a tag that comes before the printf statement. The program will jump to the position where label1 is located when the statement goto label1; is executed, and then continue to execute the code after the label. In this example, the program will output numbers 0 to 4, followed by “End of program.” Due to the use of the goto statement, the program will repeatedly execute the printf statement in a loop until the value of i is greater than or equal to 5.
It is important to note that the misuse of the “goto” statement in a program can make the code structure messy and difficult to read and maintain. Therefore, it is advisable to avoid using the “goto” statement as much as possible and instead use more structured control flow statements such as if-else, for, and while to achieve the same logic.