M.M*_*M.M 5 c gcc switch-statement fall-through
代码示例:
int main(int argc, char **argv)
{
switch(argc)
{
case 0:
argc = 5;
__attribute__((fallthrough));
case 1:
break;
}
}
Run Code Online (Sandbox Code Playgroud)
仅使用gcc 6.3.0,-std=c11此代码给出警告:
<source>: In function 'main':
7 : <source>:7:3: warning: empty declaration
__attribute__((fallthrough));
^~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
在不引起警告的情况下使用此方法的正确方法是什么?
试图评论以前,但没有 50 声望。
所以,我的经验:
1) 该功能从 gcc 7 开始,因此在较旧的编译器上使用属性会发出警告。因此我目前使用:
#if defined(__GNUC__) && __GNUC__ >= 7
#define FALL_THROUGH __attribute__ ((fallthrough))
#else
#define FALL_THROUGH ((void)0)
#endif /* __GNUC__ >= 7 */
Run Code Online (Sandbox Code Playgroud)
然后我FALL_THROUGH;在代码中使用
(总有一天我会弄清楚 clang 需要什么,但不是今天)
2)我花了相当多的时间来尝试让 gcc标记注释起作用,但我尝试过的没有任何效果!有人建议一些评论,为了使其工作,必须添加-C到
gcc参数(意味着评论将传递给cc1)。当然 gcc 7 文档没有提到关于这个要求的任何内容......
如先前的回答,__attribute__ ((fallthrough))在GCC 7中引入了。为了保持向后兼容性,并清除到秋季两个锵和海湾合作委员会警告,你可以使用/* fall through */ 标记注释。
应用于您的代码示例:
int main(int argc, char **argv)
{
switch(argc)
{
case 0:
argc = 5;
/* fall through */
case 1:
break;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5235 次 |
| 最近记录: |