在 C 中使用宏时遇到问题。
我有一个宏(这个宏只是我为重现问题而创建的一个宏,请不要评论这个宏没用的事实):
#define my_macro(x) \
({ \ // This is line 5
typeof(x) _x = x; \
typeof(x) res = x; \
\
if (_x < 0) \
_x = _x * (-1); \
for (typeof(x) _i = 0; _i < _x; _i++) \
res = res * x; \
res; \
})
我在我的程序中这样使用:
int main (int argc, char **argv)
{
printf("%d\n", my_macro(atoi(argv[1]))); // This is line 19
return (0);
}
当我使用 asso gcc
:编译程序时gcc test.c -Wpedantic
,这会导致警告:
warning: ISO C forbids braced-groups within expressions [-Wpedantic]
5 | ({ \
| ^
note: in expansion of macro main_test’
19 | printf("%d\n", my_macro(atoi(argv[1])));
| ^~~~~~~~~
在这篇文章的评论中,他们谈到了添加__extension__
以删除警告。但是,即使删除了警告,我认为这也不会使宏 ISO 兼容。
我在这里还发现使用 ado {} while (0);
可以修复警告(我自己没有尝试过,因为它不是我想要使用的解决方案)。但我觉得这更像是绕过而不是真正的答案。
所以我想知道如何解决这个问题。如果使用答案__extension__
并且缺少信息,我真的很想得到你的解释。我也没有设法找到关于究竟是什么的解释braced-groups
。如果有人可以在评论中解释它们,我很乐意阅读并理解我的错误。
总体而言,任何帮助将不胜感激,在此先感谢