I'm looking at some code that has a function that looks like this:
void f(A* a, B& b, C* c)
{
(void)a;
(void)b;
(void)c;
}
What exactly does the (void) at the start of every line do?
What you see there is really just a "trick" to fake variable/parameter usage.
Without those lines, a pedantic compiler will warn you about the variables not being used.
Using a construct (void)variablename;
will result in no instructions being generated, but the compiler will consider it a valid "use" of those variables.
It's simply a kludge to avoid compiler warnings. For example, that code will emit
warning: unused parameter ‘a’ [-Wunused-parameter]
warning: unused parameter ‘b’ [-Wunused-parameter]
warning: unused parameter ‘c’ [-Wunused-parameter]
when compiled with gcc -Wall -Wextra
if the kludge is not used. There are cleaner looking ways to achieve this though. You could omit the parameter names:
void f(A*, B&, C*) {
}
A gcc-specifc and somewhat verbose alternative is to use the unused
attribute on each unused parameter:
void f(A* a __attribute__((unused)), B& b, C* c) {
}
I see at least two rerasons. The first one is to avoid warnings of the compiler that the variables are defined but not used in the body of the function.
The second one is that it is very old code and sometimes programmers wrote casting to void before expressions if the result of the expressions is not used. This helped the compiler to optimize generated object code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With