作者 dzwei (Args&&... args)
標題 Re: [問卦] 所以寫程式用goto到底是好還是不好?
時間 Wed Oct  4 20:12:34 2023


幾十年前有陣子
不少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 (臺灣)
※ 作者: dzwei 2023-10-04 20:12:34
※ 文章代碼(AID): #1b7LQrBn (Gossiping)
※ 文章網址: https://www.ptt.cc/bbs/Gossiping/M.1696421557.A.2F1.html
※ 同主題文章:
Re: [問卦] 所以寫程式用goto到底是好還是不好?
10-04 20:12 dzwei
snow3804: 好
我都用goto來報復公司1F 36.225.230.83 台灣 10/04 20:13
i386: 不會正確用goto的才在那邊叫人不要用3F 101.136.223.74 台灣 10/04 20:15
※ 編輯: dzwei (140.112.101.44 臺灣), 10/04/2023 20:16:55
AzureRW: 我Java都把try catch當goto用 報復社會4F 219.68.123.199 台灣 10/04 20:17
ninimiga: 個人比較擅長使用switch case5F 101.137.22.109 台灣 10/04 20:19
wpd: 講中文好嗎?????????6F 36.231.169.82 台灣 10/04 20:20

--
作者 dzwei 的最新發文:
點此顯示更多發文記錄