switch语句中的独立break(standalone break within a switch statement)

编程入门 行业动态 更新时间:2024-10-28 10:28:04
switch语句中的独立break(standalone break within a switch statement)

我偶然发现了这个代码,它按预期工作:

switch (ev->deviceType) { break; case DEVICE_TS1E0: //some code break; case DEVICE_TS1E3: //some code break; default: //some logging break; }

现在,有一个寂寞的break; 在开关开始时,似乎没有效果。

有什么情况可以break; 会有影响吗?

I stumbled upon this code, which works as expected:

switch (ev->deviceType) { break; case DEVICE_TS1E0: //some code break; case DEVICE_TS1E3: //some code break; default: //some logging break; }

Now, there's a lonesome break; at the start of the switch, which appears to have no effect.

Is there any circumstances where that break; would have an effect ?

最满意答案

TL; DR那个break语句无效且是死代码。 控制永远不会到达那里。

C11标准有一个类似案例的相当不错的例子,让我直截了当地引用。

从章节§6.8.4.2/ 7开始,( 强调我的

示例在人工程序片段中

switch (expr) { int i = 4; f(i); case 0: i = 17; /* falls through into default code */ default: printf("%d\n", i); }

标识符为i的对象存在自动存储持续时间(在块内)但从未初始化,因此如果控制表达式具有非零值,则对printf函数的调用将访问不确定的值。 同样, 无法访问函数f调用。

TL;DR That break statement is ineffective and a dead-code. Control will never reach there.

C11 standard has a pretty good example of a similar case, let me quote that straight.

From Chapter §6.8.4.2/7, (emphasis mine)

EXAMPLE In the artificial program fragment

switch (expr) { int i = 4; f(i); case 0: i = 17; /* falls through into default code */ default: printf("%d\n", i); }

the object whose identifier is i exists with automatic storage duration (within the block) but is never initialized, and thus if the controlling expression has a nonzero value, the call to the printf function will access an indeterminate value. Similarly, the call to the function f cannot be reached.

更多推荐

本文发布于:2023-08-02 16:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1378703.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   独立   switch   statement   standalone

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!