我偶然发现了这个代码,它按预期工作:
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.
更多推荐
发布评论