return -2 : is there a clean way to exit parent function from a nested function?

12 ビュー (過去 30 日間)
Jonas
Jonas 2015 年 1 月 15 日
コメント済み: Jonas 2015 年 1 月 15 日
I have a parent function and several nested functions. I would like to be able, in a nested function instead of doing "return" and go back to the parent function, to do some kind of "return-2" and also exit the parent function (not only the nested one).
Is there a clean way to do it?
(I know that I can use some "flag" variable, and then in the parent function have each time "if flag; return", but I want to avoid to have duplicated code, if possible.)
  2 件のコメント
Geoff Hayes
Geoff Hayes 2015 年 1 月 15 日
Jonas - do you mean nested function or nested loop?
Jonas
Jonas 2015 年 1 月 15 日
Nested function.

サインインしてコメントする。

採用された回答

Image Analyst
Image Analyst 2015 年 1 月 15 日
As far as I know, the flag way you described is the clean way to do it. You dive in and then you bubble back up the reverse direction you went in. To do it any other way, for example a "goto" statement to send you directly to some arbitrary location, would enable "spaghetti code" and is not recommended. Don't worry about putting in 3 or 4 lines - your code might be way longer than that anyway. Anyway, some alternate method of accomplishing what you want would probably be that many lines also.
  2 件のコメント
John D'Errico
John D'Errico 2015 年 1 月 15 日
I could see the idea of a variable return, IF it were possible, as creating far too many bugs with the stack than it is worth. Just like the idea of a goto - a bad idea in terms of code flow, and not really that useful.
Jonas
Jonas 2015 年 1 月 15 日
Ok, thank you for all your answers and comments! I didn't realize that a return going up two levels may be bad.
So in my code I am doing the normal way, as Image Analyst suggested.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by