Void * func(void* arg)

I need to understand the meaning of the following function. To me I think I think It means that the data type that is being passed is unknown and it will return a pointer. Am I right? How does the function work?
.

1
2
3
   
void* func(void* arg)
.
To me I think I think It means that the data type that is being passed is unknown

Not quite. The caller will known the data type of what is being passed. It means it will accept a pointer of any type. This is generally considered not a good practice in C++.
it will return a pointer.

Yes, it will be assignable to a pointer of any type.
Both practices are hangovers from C generally not used in C++.
How does the function work?

What function? You have posted only the function header, not the function itself.


Last edited on
> It means that the data type that is being passed is unknown

Yes, it is unknown from the declaration of the function; all that we know is that it is an object pointer type.


> it will return a pointer.

Yes, return an object pointer


> How does the function work?

If it tries to do anything with the pointed-to-object, and it mis-guesses the type, it won't work at all (the function is not type-safe).
How does the function work?

Since you are only showing us the signature of the function, not the actual implementation (code, or function body), it is impossible to know what the function does and how.

You can think of an untyped void* pointer as a memory address, but no information what is at that address.

Conversely, a typed int* pointer would be the address of an int value (supposedly).

Anyhow, a typical example of a function that takes untyped void* pointers would be memcpy():
void * memcpy(void * destination, const void * source, size_t num);

https://www.cplusplus.com/reference/cstring/memcpy/

memcpy() doesn't care about the type of the data to be copied, it just copies the data in a "byte by byte" fashion, so void* is okay here. And it's the most "general" pointer type, so memcpy() can work with any data without the need for scary type casts. But, as you see, memcpy() also needs a "num" argument, so that it can know how many bytes to copy. It couldn't know that from the pointer type, because... the pointer is untyped.
Last edited on
Passing arguments as void* is used in MPI all the time - but you have to make sure that the function knows how many items of what type of data is being passed.

The type of data is better described as "general" rather than "unknown" - somehow the function needs to know what to do beyond the memory location pointed to (usually how many items of objects occupying a certain number of bytes).
Last edited on
Topic archived. No new replies allowed.