I've got a question. Let's say you define a function or variable in C. If you don't use it, the compiler generates a warning that this variable/function wasn't used. To suppress the warning, you use the __unused
attribute before the declaration. If you have to use that, what's the point of declaring a function/variable in the first place? What's good about using __unused
?

- 24,970
- 5
- 40
- 69

- 599
- 1
- 6
- 19
-
5There are many cases. A common example is callback functions that you need to provide to an API. You can't change the callback signature as that is defined by the API. The callback signature includes parameters that some other callback providers will use but is not needed in your callback implementation. – kaylum Jan 07 '21 at 22:08
-
Thanks @kaylum but will that function get unused once the __unused attribute is passed? – Matthew Schell Jan 07 '21 at 22:17
-
Not the function but rather one or more of the parameters passed to the function. The caller of the function will always pass in some value for that parameter but your function implementation does not use it. – kaylum Jan 07 '21 at 22:17
-
1No, the function won't be unused (at least, not because of the `__unused` attribute). But the compiler won't complain about the unused arguments being unused because the attribute says they aren't used. – Jonathan Leffler Jan 07 '21 at 22:18
1 Answers
__unused
is usually a macro that expands to a C language extension. However, C23 will give us [[maybe_unused]]
, and the standard comes with an example:
EXAMPLE
[[maybe_unused]] void f([[maybe_unused]] int i) { [[maybe_unused]] int j = i + 100; assert(j); }
Implementations are encouraged not to diagnose that
j
is unused, whether or notNDEBUG
is defined.
That is, the assert()
macro will expand to nothing in NDEBUG
, which means the compiler will think j
is not used.
Of course, an alternative to this would be to put the entire j
definition (and optionally its usage) inside an #ifdef
"block", but that would be cumbersome in this case. Furthermore, if you do that, then i
would be the one unused, etc.
There are other use cases, like unused function parameters if you want to keep their names and avoid the (void)x;
trick, dealing with a confused optimizer/compiler in some cases, external uses of symbols that cannot be seen by the compiler/linker, etc.

- 24,970
- 5
- 40
- 69