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?
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.
Whenever we are writing a function in C++, we need to follow prototype of function, i.e.
type name ( parameter1, parameter2, ...) { statements }
here type- stands for type of value it returns
A return type of void allows you to define a function that does not return a value. Note that it is NOT the same as returning 0. The value of 0 is of type integer, float, double, etc; it is not a void. (In other languages, a function with no return value may be called a "subroutine" or "procedure", whereas a "function" always returns something. In C/C++, they are all called functions.) returning void means returning nothing.
A pointer to void is a generic pointer that can be used when the type of the data at the location is unknown. So you can use a type of void * to refer to an address in memory without knowing what is actually located there.