Reputation: 679
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
?
Upvotes: 1
Views: 2383
Reputation: 26136
__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.
Upvotes: 1