Consider the following main()
:
int main(int argc, char *argv[])
{
return (0);
}
Upon compilation with cc -Wall -Wextra
, warnings saying "unused parameter" get generated.
When I do not need to use a parameter in a function (for instance in a signal handler function that makes no use of its int
parameter), I am used to doing the following:
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
return (0);
}
(For that particular
main()
, I sometimes see other people do:argv = argv - argc + argc
)
But what does (void)var
actually do?
I understand that (void)
is a cast, so I guess I am casting away the variable? What does the var;
line (without the cast) do? Is it an empty assignment, an empty expression?
I would like to understand what is actually going on.
A void function with value parameters are declared by enclosing the list of types for the parameter list in the parentheses. To activate a void function with value parameters, we specify the name of the function and provide the actual arguments enclosed in parentheses.
When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal." If a pointer's type is void* , the pointer can point to any variable that's not declared with the const or volatile keyword.
The literal meaning of void is empty or blank. In C, void can be used as a data type that represents no data.
It's just a way of creating a 'harmless' reference to the variable. The compiler doesn't complain about an unused variable, because you did reference the value, and it doesn't complain that you didn't do anything with the value of the expression var
because you explicitly cast it to void (nothing), indicating that you didn't care about the value.
I haven't seen this usage on variables before (because the compiler I use doesn't normally complain about unused function arguments,) but I see this used frequently to indicate to the compiler that you don't really care about the return value of a function. printf(),
for example, returns a value, but 99% of C programmers don't know (or care) what it returns. To make some fussy compilers or lint tools not complain about an unused return value, you can cast the return value to void, to indicate that you know it's there, and you explicitly don't care about it.
Other than communicating your intent (that you don't care about this value) to the compiler, it doesn't actually do anything - it's just a hint to the compiler.
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