Is it true that goto jumps across bits of code without calling destructors and things?
e.g.
void f() {
int x = 0;
goto lol;
}
int main() {
f();
lol:
return 0;
}
Won’t x be leaked?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Warning: This answer pertains to C++ only; the rules are quite different in C.
No, absolutely not.
It is a myth that
gotois some low-level construct that allows you to override C++’s built-in scoping mechanisms. (If anything, it’slongjmpthat may be prone to this.)Consider the following mechanics that prevent you from doing “bad things” with labels (which includes
caselabels).1. Label scope
You can’t jump across functions:
2. Object initialisation
You can’t jump across object initialisation:
If you jump back across object initialisation, then the object’s previous “instance” is destroyed:
You can’t jump into the scope of an object, even if it’s not explicitly initialised:
… except for certain kinds of object, which the language can handle regardless because they do not require “complex” construction:
3. Jumping abides by scope of other objects
Likewise, objects with automatic storage duration are not “leaked” when you
gotoout of their scope:Conclusion
The above mechanisms ensure that
gotodoesn’t let you break the language.Of course, this doesn’t automatically mean that you “should” use
gotofor any given problem, but it does mean that it is not nearly as “evil” as the common myth leads people to believe.