I'm facing an issue while using macros in C.
I have a macro (this macro is just a macro I've create to reproduce the issue, please do not comment the fact that this macro is useless) :
#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; \
})
That I use in my program as so :
int main (int argc, char **argv)
{
printf("%d\n", my_macro(atoi(argv[1]))); // This is line 19
return (0);
}
When I compile my program using gcc
as so : gcc test.c -Wpedantic
, this leads to a warning :
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])));
| ^~~~~~~~~
In comments of this post they talk about adding __extension__
to remove the warning. But even if the warning is removed, this does not make the macro ISO Compliant I think.
I've also found here that using a do {} while (0);
could fix the warn (I did not try that myself since it's not the solution I would like to use). But I feel like this is more a bypass than a real answer.
So I'm wondering how I could fix this.
If the answer to use __extension__
and am missing information and I would really like to have your explanations on this.
Also I did not manage to find explanations on what exactly are braced-groups
. If anyone could please explain them in comments I would be happy to read this and understand my mistake.
Overall any help would be appreciate, Thanks by advance