What is "better" : (x=x) or (void(x)) for unused parameters?

Viewed 231

Well we all know that sometimes we get parameters to a function but we don't really use them.

We don't want to get any compiler warnings so we need to somehow "use" but not really use those parameters.

2 options are available to us:

#define UNUSED(x) (void)(x)

#define UNUSED(x) (x=x)

and in general, to define (x=x) or void(x) in a function, even without #define.

The question is:

Which one of these is "better"?

Better for performance (quicker), memory allocation(if any), anything you can think about speaking technically.

2 Answers

(void)x is part of the standard, so it should be better. You won't get compilers/linters warnings when you use it. It is also portable, unlike implementation-specific solutions like __attribute__((unused)) and it will not generate any code. x = x may generate warnings.

An example regarding the warnings that can be emitted for x=x:

int foo(int bar)
{
    bar = bar;
    return 1;
}

int main()
{
    return foo(2);
}

Compiling the above code with -Wall (or just -Wself-assign) with Clang 10 triggers the following warning:

$ clang test.c -Wall
test.c:3:9: warning: explicitly assigning value of variable of type 'int' to itself [-Wself-assign]
    bar = bar;
    ~~~ ^ ~~~

Same goes for linters like cppcheck:

$ cppcheck test.c --enable=all
Checking test.c ...
test.c:3:9: warning: Redundant assignment of 'bar' to itself. [selfAssignment]
    bar = bar;
        ^
test.c:3:9: style: Variable 'bar' is assigned a value that is never used. [unreadVariable]
    bar = bar;
        ^

Of course, these depend on the tools you use and the warnings you enable, so it may or may not generate warnings, but casting an expression to void will never generate these kind of warnings.

Which one of these is "better"?

#define UNUSED(x) (void)(x)

Because it's pretty much standard for what you're doing anyway.

Better for performance (quicker), memory allocation(if any), anything you can think about speaking technically.

If you have optimization activated, which you should if you care about performance, these things will be optimized away anyway.

Related