Goto c как использовать
Перейти к содержимому

Goto c как использовать

  • автор:

goto Statement in C

The C goto statement is a jump statement which is sometimes also referred to as an unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function.

Syntax:

In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label. Here, the label is a user-defined identifier that indicates the target statement. The statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax.

goto statement in C

Flowchart of goto Statement in C

Below are some examples of how to use a goto statement.

Examples:

Type 1: In this case, we will see a situation similar to as shown in Syntax1 above. Suppose we need to write a program where we need to check if a number is even or not and print accordingly using the goto statement. The below program explains how to do this:

goto Statement in C

Goto statement in C is a jump statement that is used to jump from one part of the code to any other part of the code in C. Goto statement helps in altering the normal flow of the program according to our needs. This is achieved by using labels, which means defining a block of code with a name, so that we can use the goto statement to jump to that label. Goto statement can be used in two ways: either to skip some lines and move to a block below in the code or to repeat some lines of code by going above in the code.

What is goto Statement in C?

Consider you have signed up for an advanced course for a subject after you completed it's beginner course. The first few lessons of this course revise the beginner topics for students who are new to the subject. But you have already studied these, so you will skip these beginner lectures, and directly goto the lectures where the advanced lesson starts.

Consider another case where you signed up for a different advanced course for another subject. But this time you didn't take its beginner course and there are no revision lectures hence your tutor instructed you to first get familiar with the beginner course. In this case you first goto the beginner course and then come back to finish this advanced course.

Similarly, we may need to jump from one line to another in our program to either goto skip a few lines or to first execute some block of code and then arrive at this one. This is exactly where the goto statement is used.

Goto statement is a form of jump statement, it is used to jump from one block to another block during execution. It is often also termed as an unconditional jump statement.

Syntax of goto Statement in C

The syntax of goto statement in C can be broken into two parts:

1. Defining the Label

  • The label_name is used to give a name to a block of code, hence it acts as an identifier for that block. When a goto statement is encountered, the program's execution control goes to the label_name: and specifies that the code will be executed from there.
  • We need to always use : (colon) after the label_name
  • Each label_name has to be unique in the scope where it has been defined and cannot be a reserved word, just like in variables.

2. Transferring the Execution Control

  • The above statement jumps the execution control of the program to the line where label_name is used.

Now by combining the above two parts, we get the full syntax of the goto statement in C. However there's a catch, We can combine the above two parts in two different ways.

Style 1: Transferring the Control From Down to the Top

Style 2: Transferring the control from top to down

Before we move on to discussing these two methods in detail, let’s take a look at the general flow diagram of the goto statement in C.

Flow Diagram of goto Statement in C

As visible in the flow diagram, as soon as we arrive at the goto statement, the control of the code is transferred to wherever the label has been defined.

In this case, the label has been defined below the goto statement. Hence, the statements between the goto statement and the label declaration are skipped.

On the other hand, the label can also be declared before the goto statement. In this case, no statement is skipped, instead, the statements between the goto statement and the label declaration are repeated.

This has been shown in the image below.

Now, let’s take a look at the two styles we introduced above in detail.

Two Styles of goto Statement in C

There are two different styles of implementing goto statements in C. Either the label is declared above the call of the goto statement, which is the first case, or the label is declared after the call of the goto statement.

In the first style, the flow control shifts from the lower to some upper part of the code, while in the second style the flow control shifts from the upper part to the lower part of the code, maybe skipping some lines in between.

Let us look at both of these styles in detail to understand more.

Style 1: Transferring the Control from Down to the Top

In this style, the control is transferred to a part of the program which is above the goto statement. This results in a kind of loop in the program. We will see this more clearly in the example.

Let's take a look at a modified and well-defined syntax again:

In the above pseudo-code, when and if the condition is true the program execution control will be transferred to label_name. Let’s take an example where we might use such logic.

Example 1: To print numbers using the goto statement

Output

It is clear from this program that whenever curr is less than the end , we repeat the printing part until curr becomes equal to the end . At that point, the condition inside if becomes false, and the goto statement isn't executed.

This is exactly how a goto statement can create a loop in a program, without using for or while loops. However, in most cases goto statements are used only for flow control, to dictate where the control of the program should be transferred next.

Style 2: Transferring the Control from Top to Down

This style has the same syntax, with the only exception being that the label is declared after the goto statement is called. This means that in this case, the control is transferred to a part of the program which is below the goto statement.

Let us take a took at the syntax:

In the above pseudo-code, if the condition is true, the control is passed on to the label block. Let's see an example.

Example 2: To Find Ceil Division of Two Numbers

Output

In this program, we add one to the answer only if a is not divisible by b , else the program goes straight to the print_line label because of the goto statement. Thus, in this way, the goto statement helps in transferring the control in the code.

How Does the goto Statement Work in C?

Goto statement helps in transferring the execution of the program from one line to another. That is why it is a jump statement, as it enables us to jump from one part of our program to another.

This is done by using the goto statement and a label name as defined above in the syntax. Whenever the compiler arrives at a goto statement, it transfers the execution of the program from that line to the line where the label has been defined. Then the execution again starts from that point. Another point to note is that the label can be defined before or after using the goto statement, but it should be present in the code.

As it is clear, we jumped from one part of the code to another, hence goto is an unconditional jump statement.

Program to Understand the goto Statement in C

Let us look at a program to output the absolute value of any integer in C, and how goto statement can be used in it.

Output

We skip the 17th line if the number is positive by using the goto statement. When the code enters the if block in line 10 in case of a positive number, it is directed to where the positive label has been declared, which means to the 21st line. Else, the number is multiplied by -1 to get its absolute value and this value is printed.

Goto Statement in C Example

Let us look at a few more examples to understand more clearly.

Example 1: Find the Square Root of Positive Numbers in C

Output

As is clear from the code, if a negative number has been entered, to avoid error we jump to the end using the goto statement and print that a negative number has been entered.

Example 2: Break out of nested loops using goto statement in C

Output

In the code we have three loops running, if we wanted to break out of all three of them together at once, we would have to write three break statements, one for each loop. But, in this code as we have defined the label after the three nested loops, we can use just one goto statement and break out of all three nested loops.

When Should We Use the goto Statement?

In any case, where you need to make a jump from one part of the code to another, you can use the goto statement. It can be used to move to any place within the function where the goto statement is called, depending upon where the label referred to by the goto statement has been declared.

It is important to note that using goto statements we can even jump to a part of the code in our program which we have already passed and executed once if the label has been defined above the goto statement. This was the first style discussed above. This is unlike many other jump statements like a break, which transfer the code execution to a part somewhere below the current execution.

Advantages of goto Statement in C

  • Goto is a jump statement that can alter the normal flow of execution of code. Using the goto statement, you can not only jump to a part of the code below the current flow but also a part above the current flow.
  • This also enables goto statements to initiate loops in the program, without using for or while in the code.
  • We can also use goto statement when a certain condition is satisfied, and skip some lines of code altogether by moving to another part of the program.
  • goto statements can be helpful when you want to break out of nested loops. Using one goto statement, you can break out of all loops, instead of using multiple break statements.

Disadvantages of goto Statement in C

Goto statements, although help in jumping from one part of the code to another, make code unreadable. Just imagine having more than two or three goto statements in a program, and trying to figure out which goto statement leads the code to which part. As goto statements alter the normal flow of execution of the program, it can become difficult to understand the new flow when goto statements are added. This makes code unreadable and dirty.

Let us take an example to understand it better.

Output

This code looks straight enough and runs fine, but only for odd numbers. If you look closely, this code goes into an infinite loop for even numbers because of line 24. This little cycle is being formed due to the goto statement in this line, and it is difficult to figure it out because of the changing flow of execution of the code due to the goto statements.

This is just a small example of how goto statements can cause unwanted loops and errors in programs if not used with caution.

Урок №66. Оператор goto

Оператор goto — это оператор управления потоком выполнения программ, который заставляет центральный процессор выполнить переход из одного участка кода в другой (осуществить прыжок). Другой участок кода идентифицируется с помощью лейбла. Например:

В этой программе пользователю предлагается ввести неотрицательное число. Однако, если пользователь введет отрицательное число, программа, используя оператор goto, выполнит переход обратно к лейблу tryAgain . Затем пользователю снова нужно будет ввести число. Таким образом, мы можем постоянно запрашивать у пользователя ввод числа, пока он не введет корректное число.

Ранее мы рассматривали два типа области видимости: локальная (или «блочная») и глобальная (или «файловая»). Лейблы используют третий тип области видимости: область видимости функции. Оператор goto и соответствующий лейбл должны находиться в одной и той же функции.

Существуют некоторые ограничения на использование операторов goto. Например, вы не сможете перепрыгнуть вперед через переменную, которая инициализирована в том же блоке, что и goto:

В целом, программисты избегают использования оператора goto в языке C++ (и в большинстве других высокоуровневых языков программирования). Основная проблема с ним заключается в том, что он позволяет программисту управлять выполнением кода так, что точка выполнения может прыгать по коду произвольно. А это, в свою очередь, создает то, что опытные программисты называют «спагетти-кодом». Спагетти-код — это код, порядок выполнения которого напоминает тарелку со спагетти (всё запутано и закручено), что крайне затрудняет следование порядку и понимание логики выполнения такого кода.

Как говорил один известный специалист в информатике и программировании, Эдсгер Дейкстра: «Качество программистов — это уменьшающаяся функция плотности использования операторов goto в программах, которые они пишут».

Оператор goto часто используется в некоторых старых языках, таких как Basic или Fortran, или даже в языке Cи. Однако в C++ goto почти никогда не используется, поскольку любой код, написанный с ним, можно более эффективно переписать с использованием других объектов в языке C++, таких как циклы, обработчики исключений или деструкторы (всё перечисленное мы рассмотрим чуть позже).

Правило: Избегайте использования операторов goto, если на это нет веских причин.

C goto Statement

In this tutorial, you will learn to create the goto statement in C programming. Also, you will learn when to use a goto statement and when not to use it.

The goto statement allows us to transfer control of the program to the specified label .

Syntax of goto Statement

The label is an identifier. When the goto statement is encountered, the control of the program jumps to label: and starts executing the code.

How goto statement works?

Working of goto Statement

Example: goto Statement

Output

Reasons to avoid goto

The use of goto statement may lead to code that is buggy and hard to follow. For example,

Also, the goto statement allows you to do bad stuff such as jump out of the scope.

That being said, goto can be useful sometimes. For example: to break from nested loops.

Should you use goto?

If you think the use of goto statement simplifies your program, you can use it. That being said, goto is rarely useful and you can create any C program without using goto altogether.

Here’s a quote from Bjarne Stroustrup, creator of C++, «The fact that ‘goto’ can do anything is exactly why we don’t use it.»

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *