Void pointer initialization? If not, what is it?

I am trying to understand a segment of code used as a parameter in C ++, but I cannot find another example of this elsewhere on the internet. Here's a segment:

void (*cb)(void)

      

Is this another way to initialize a void pointer? What is the use of this, for example, from void *cb

?

+3


source to share


2 answers


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

for example if i have

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

      

then later I could

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

      

I can call the function using:

cb(); 

      

which is called by printHello ();



The utility of this is that I can now assign different functions to cb and call them and pass them 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 gulp:

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

      

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

int (*ptrToFunctionReturningInt)(void);

      

and a pointer to a function that takes an int and returns nothing would look like this:

void (*ptrToFunctionReturningNothing)(int);

      

+9


source


cb

is a pointer to a function that takes no arguments and does not return a value.



It is often used to implement callback mechanisms: i.e. if it is passed to a function, then that function can be called cb

using cb()

;

+2


source







All Articles