pranathi
pranathi

Reputation: 393

What does this C function mean ? A function pointer?

I would like to know what this C function exactly mean ?

typedef uint32_t (*test) ( void );

Upvotes: 2

Views: 129

Answers (2)

John Bode
John Bode

Reputation: 123598

It basically reads as:

                     test                  -- test is
typedef              test                  -- a typedef name (alias) for the type
typedef             *test                  -- pointer to
typedef            (*test)     (      )    --   a function taking
typedef            (*test)     ( void )    --     no parameters
typedef uint32_t   (*test)     ( void );   --   returning uint32_t

So test is an alias for the type "pointer to a function taking no parameters and returning uint32_t (uint32_t (*)(void)).

So if you had a function like

uint32_t foo(void) { return some_value; }

then you could create a pointer to that function using either

uint32_t (*ptr)(void) = foo;

or

test ptr = foo;

As a matter of style, it's usually a bad idea to hide the pointer-ness of a type in a typedef1; it would be better to create a typedef like

typedef uint32_t test(void); // test is a typedef name for "function taking no parameters
                             // and returning uint32_t

and then create the pointer as

test *ptr;

  1. Unless you're prepared to write a complete abstraction layer that handles all the pointer operations and hides them from the user, in which case go nuts.

Upvotes: 4

kaylum
kaylum

Reputation: 14044

It is a typdef of a function pointer to a function that takes no args and returns a uint32. So not an actual function pointer but an alias for that type.

An example of how to use it:

#include <stdio.h>
#include <stdint.h>

typedef uint32_t   (*test)     ( void );

uint32_t my_test1(void)
{
    return 100;
}

// Output of this program will be: 100
int main (void)
{
    test func = my_test1;
    printf("%d\n", func());
}

Upvotes: 3

Related Questions