即使前一行导致退出,也使用break语句

发布于 2024-09-08 13:44:29 字数 309 浏览 7 评论 0原文

今天我正在阅读一些代码(C,如果它对任何人都有影响的话),并对开关块感到好奇。

switch (c_type) {
case -1:
    some_function(some_var);
    break;
[...]
default:
    abort();
}

现在,这是一个非常简单的开关块。我很好奇的是 some_function(some_var) 调用:如果你,程序员,绝对、肯定、超级确信调用会导致进程退出,你还会把即使完全没有必要,也要在下面添加break语句吗?您会说这是最佳实践吗?

I was reading through some code (C, if it makes a difference to anyone) today and got curious about a switch-block.

switch (c_type) {
case -1:
    some_function(some_var);
    break;
[...]
default:
    abort();
}

Now, this is a perfectly simple switch-block. It's the some_function(some_var)-call I'm curious about: If you, the programmer, is absolutely, positively, super duper sure that the call will result in the process exiting, do you still put the break-statement underneath even though it is completely unnecessary? Would you say that it is best-practice?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

稀香 2024-09-15 13:44:29

我想说,最佳实践是在函数调用下方添加一个炸弹 assert() 。这有双重目的:它记录了运行时中的这一点应该无法到达的事实,并且如果代码确实到达了该点,它会生成一条错误消息。

I would say best practice would be to have a bomb-out assert() below the function call. This serves a dual purpose: it documents the fact that this point in the runtime should be unreachable, and it produces an error message if the code somehow does reach that spot.

深海蓝天 2024-09-15 13:44:29

把休息时间留在那里。 您确信什么并不重要:您编写程序供其他人阅读,并且中断清楚地表明给定的情况与随后的情况完全分开。

即使您今天可以绝对确定代码,但明天规范可能会发生变化,并且 some_function 将不再退出。规格中没有什么是确定的(无论如何,根据我的经验)。

Leave the break in there. It doesn't matter what you are sure about: you write your programs for other humans to read, and the break makes it clear that the given case is completely separate from the case that follows.

Even though you could be absolutely certain about the code today, the specification may change tomorrow and some_function won't exit anymore. Nothing in specifications is certain (in my experience anyway).

风和你 2024-09-15 13:44:29

如果我超级确定调用会导致进程退出,我会为此添加一个断言。

这样,如果有人修改了该函数并且该函数并不总是终止,则该错误几乎会在第一次发生时就被捕获。

编辑:被击败,答案也几乎相同:/

If I'm super-duper-super-sure that the call would result in the process exiting, I'd stick an assert in just for that.

That way, if someone modifies the function and it doesn't always-terminate, the bug will be caught pretty much the first time it occurs.

EDIT: Beaten, with pretty much the same answer too :/

三生路 2024-09-15 13:44:29

最好的做法是用break或return结束每个case语句,除非您希望它继续到下一个。

It's always best practice to end every case statement with a break or return, unless you want it to fall through to the next.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文