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?
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.
Advertisements. A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement in the same function.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With