Dipesh Kumar Gupta
Dipesh Kumar Gupta

Reputation: 33

Pointer to a function and its return type (void)

Is such declaration void *(*function) () is valid ? If it is valid then *function will return any address to called function . At that address, what value is returning? Is value save at that address is 0. If it is zero,what is the difference between return 0 and return nothing in function having return type void.

Upvotes: 1

Views: 8628

Answers (2)

John Bode
John Bode

Reputation: 123448

The declaration is read as follows:

        function        -- function is a 
       *function        -- pointer to 
      (*function) ()    -- function taking unspecified parameters
     *(*function) ()    -- returning pointer to
void *(*function) ();   -- void

So, function is a pointer to a function type, not a function itself. You could have multiple functions, each returning pointers to void:

void *foo( void )    { ... }
void *bar( void )    { ... }
void *bletch( void ) { ... }

You can use the function pointer to point to each of those functions, and decide at runtime which to call:

if ( condition1 )
  function = foo;
else if ( condition2 )
  function = bar;
else
  function = bletch;

void *ptr = function(); // or (*function)();

Upvotes: 3

templatetypedef
templatetypedef

Reputation: 372784

The notation

void * (*function)();

means “declare a function pointer named function, which points to a function that takes an unspecified number of arguments, then returns a void *.”

Since this just declares a variable, it doesn’t define a function and so nothing can be said about what value is going to be returned. You’d need to assign this pointer to point to a function before you can call it.

Once you do assign function to point to something, if you call function, you’ll get back a void *, which you can think of as “a pure memory address” since it contains an address but can’t be dereferenced to an object without a cast.

Notice that returning a void * is not the same as as a function that has a void return type. The former means “I return a memory address,” and the latter means “I don’t return anything at all.”

Upvotes: 2

Related Questions