Re: [問卦] 所以寫程式用goto到底是好還是不好?已刪文

看板Gossiping作者 (Args&&... args)時間2年前 (2023/10/04 20:12), 2年前編輯推噓1(213)
留言6則, 5人參與, 2年前最新討論串2/2 (看更多)
幾十年前有陣子 不少style或者公司禁用 是怕寫成"麵糊糰"程式 導致難以維護 https://i.imgur.com/qcqJrIE.png
但我們看看這些人怎麼說: google style C++: https://google.github.io/styleguide/cppguide.html for example, goto contravenes many of the following principles, but is already vanishingly rare, so the Style Guide doesn’t discuss it 上面的意思 說的大概是指 goto有不少問題 大家心裡有數 這份文件就不討論了 Linux Kernel或者一些device drive 的"下水道風格" 依然運作於新程式中 int foo(int bar) { int return_value = 0; allocate_resources_1(); if (!do_something(bar)) goto error_1; allocate_resources_2(); if (!init_stuff(bar)) goto error_2; allocate_resources_3(); if (!prepare_stuff(bar)) goto error_3; return_value = do_the_thing(bar); error_3: cleanup_3(); error_2: cleanup_2(); error_1: cleanup_1(); return return_value; } 上面這段程式 https://tinyurl.com/4djyvcnn 就是所謂的"下水道風格" 那不用goto會怎樣? int foo(int bar) { int return_value = 0; allocate_resources_1(); if (do_something(bar)) { allocate_resources_2(); if (init_stuff(bar)) { allocate_resources_3(); if (prepare_stuff(bar)) { return_value = do_the_thing(bar); } cleanup_3(); } cleanup_2(); } cleanup_1(); return return_value; } 是不是看的想罵髒話了? rust沒有goto 有人提議rust新一代的系統工具程式 應該具備goto語法 但是有人表示 設計良好的 switch-case語法(有線狀態機) 是可以免除goto https://tinyurl.com/2jt3w76k 可以看這邊討論 這種概念也可以套用到別的程式語言 結論: 不知道各位還記不記得 上面的google style 跟它一樣 很多東西都有pros. cons. 取決於 (1)使用情境 (2)使用方式 就像是開山刀 拿來開山路真的好用 但是砍人就不對了 但你也不會因為這樣就說 開山刀是不該存在世界上的毒瘤 然後jserv的goto文 也寫的很好 這邊補充 https://hackmd.io/@sysprog/c-control-flow 以上 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.112.101.44 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Gossiping/M.1696421557.A.2F1.html

10/04 20:13, 2年前 , 1F
10/04 20:13, 1F

10/04 20:13, 2年前 , 2F
我都用goto來報復公司
10/04 20:13, 2F

10/04 20:15, 2年前 , 3F
不會正確用goto的才在那邊叫人不要用
10/04 20:15, 3F
※ 編輯: dzwei (140.112.101.44 臺灣), 10/04/2023 20:16:55

10/04 20:17, 2年前 , 4F
我Java都把try catch當goto用 報復社會
10/04 20:17, 4F

10/04 20:19, 2年前 , 5F
個人比較擅長使用switch case
10/04 20:19, 5F

10/04 20:20, 2年前 , 6F
講中文好嗎?????????
10/04 20:20, 6F
文章代碼(AID): #1b7LQrBn (Gossiping)
文章代碼(AID): #1b7LQrBn (Gossiping)