Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same goto labels used in a C file but different functions

Tags:

Can someone please tell me if it is acceptable to use same goto labels in different functions in the same C file?

To explain what I am facing:

function1() {     ...      goto label      ...  label:     ... }  function2() {     ...     goto label;      ...  label:     ... } 

Now whats happening is that the code after the label is being used for cleanup of malloc'ed' data. And the whole thing is crashing in function2. I printed out the mem. locations which are being free and the same are being freed multiple times. Is this because of all the gotos? Is this valid use of the goto statement?

like image 523
user2311285 Avatar asked Apr 25 '13 07:04

user2311285


People also ask

Is it possible the goto statement used between two functions?

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

What is GOTO label in C?

Advertisements. A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement in the same function.

What is the scope of the label used in the goto statement?

Explanation. A label is an identifier followed by a colon ( : ) and a statement (until C23). Labels are the only identifiers that have function scope: they can be used (in a goto statement) anywhere in the same function in which they appear. There may be multiple labels before any statement.

How do labels work in C?

In C a label identifies a statement in the code. A single statement can have multiple labels. Labels just indicate locations in the code and reaching a label has no effect on the actual execution.


2 Answers

Labels are local, so you can use the same label in multiple functions.

The question about if you should use goto is a different matter though, and one that is not easily answered. In short, don't use goto. But as with everything (especially when it comes to programming) there are exceptions where goto may be useful.

like image 77
Some programmer dude Avatar answered Oct 01 '22 23:10

Some programmer dude


As Joachim said here, labels are local; but note that labels are local to functions - not to the current block. goto statements do not respect scoping, except for whole-function scoping.

like image 27
Elazar Avatar answered Oct 02 '22 00:10

Elazar