Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Void pointer initialization? If not, what is it?

Tags:

c++

pointers

void

I'm trying to understand a segment of code used as a parameter in C++ but I can't seem to find another example of it elsewhere on the internet. Here's the segment:

void (*cb)(void)

Is this another way of initializing a void pointer? What is the benefit of doing it like this versus void *cb?

like image 966
Konrad Avatar asked Jul 27 '26 21:07

Konrad


1 Answers

In this example, cb is a pointer to a function which takes no arguments and has no return value

for example if I have

void printHello( ) {
    cout << "hello" << endl;
}

then I could later have

void (*cb)(void);
cb = printHello;

I can call the function using:

cb(); 

which will call printHello();

The utility of this is that I can now assign different functions to cb and call them and pass them around to other functions like any other pointer variable.

Often for clarity, programmers will create a specific type for this to avoid having to write this mouthful:

typedef void (*tPrtToVoidFn)(void);
tPtrToVoidFn  cb;
cb = printHello;

For comparison, a pointer to a function that returns an int would look like:

int (*ptrToFunctionReturningInt)(void);

and a pointer to a function taking an int and returning nothing would look like:

void (*ptrToFunctionReturningNothing)(int);
like image 161
Dave Durbin Avatar answered Jul 30 '26 12:07

Dave Durbin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!