Jumping from a scope
Jumping from a scope
Is it possible to jump from an unnamed scope?
void MyFunc()
... // Code
if (!head_size)
goto _common_error; // <- break and continue don't work here
... // Code
if (!tail_size)
goto _common_error; // second time
... // Code
_common_error:
... // Code
My question is not whether this can be redesigned, but whether there is a trick in c++ that I don't know.
Is there a mechanism in c++ other than goto to jump out of an unnamed scope? break and continue do not work in scopes.
Update1: changed word namespace to scope
goto
return
break only works in a loop or switch.
– stark
Sep 2 at 11:22
Why would you want to do that? Most likely your code should be redesigned
– macroland
Sep 2 at 11:24
Please post a Minimal, Complete, and Verifiable example (code fragments don't count). And there is no namespace in the posted code.
– Richard Critten
Sep 2 at 11:26
Depending on your meaning, which is still unclear, there are options. Throwing exceptions can pass control to a caller (or, more accurately, the first caller that can catch the thrown exception), but also unwinds the stack (e.g. cleans up variables of automatic storage duration). There are also function
setjmp() and longjmp(). Calling exit() or abort() terminates the program - which, by definition, causes control to leave the current scope. A return statement passes control to the caller (which is a different scope).– Peter
Sep 2 at 12:47
setjmp()
longjmp()
exit()
abort()
return
1 Answer
1
Yes, you need to use goto to jump out of a scope.
goto
break can only be used to jump out of a loop or switch.
break
But you can use a (questionable) trick by using a dummy loop:
void MyFunc()
do
... // Code
if (!head_size)
break;
... // Code
if (!tail_size)
break;
... // Code
while (false);
... // Error handling code
cool, I like it
– B. A. Sylla
Sep 2 at 15:25
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
What are you trying to do? I have a feeling that you mean a scope, rather than an unnamed namespace. Can you give a more complete example? In C++, it is very rare to find cases when a
gotois a reasonable solution. Maybe you want areturnstatement?– Michael Veksler
Sep 2 at 11:16