What does (void) mean in C ++?

I am looking at 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 (void) do at the beginning of each line?

+5
source share
4 answers

What you see is really just a β€œtrick” to falsely use variables / parameters.

Without these lines, a pedantic compiler will warn you that variables are not used.

Using the (void)variablename; construct (void)variablename; will cause no commands to be generated, but the compiler will consider this a valid "use" of these variables.

+9
source

This is just kludge to avoid compiler warnings. For example, this code will emit

 warning: unused parameter 'a' [-Wunused-parameter] warning: unused parameter 'b' [-Wunused-parameter] warning: unused parameter 'c' [-Wunused-parameter] 

when compiling with gcc -Wall -Wextra if kludge is not used. However, there are cleaner ways to achieve this. You can omit parameter names:

 void f(A*, B&, C*) { } 

The gcc-specificc specification and somewhat verbal is to use the unused attribute for each unused parameter:

 void f(A* a __attribute__((unused)), B& b, C* c) { } 
+3
source

I see at least two records. The first is to avoid compiler warnings that variables are defined but not used in the function body.

Secondly, this is very old code, and sometimes programmers wrote casting for void before expressions if the result of the expressions is not used. This helped the compiler optimize the generated object code.

+2
source

Whenever we write a function in C ++, we need to follow the function prototype, i.e.

type name (parameter1, parameter2, ...) {statements}

here type - indicates the type of value that returns

  • The return type void allows you to define a function that does not return a value. Note that this is NOT the same as 0 returns. The value 0 is of type integer, float, double, etc .; it is not a void. (In other languages, a function without a return value can be called a "subroutine" or "procedure", while a "function" always returns something. In C / C ++, they are all called functions.) Return void means returning nothing.

  • A void pointer is a generic pointer that can be used when the data type in a location is unknown. That way, you can use the void * type to refer to an address in memory without knowing what it actually is.

-3
source

Source: https://habr.com/ru/post/1214226/


All Articles