typedef void (func_type)(void);
func_type *func_ptr;
Is this a correct way of defining a function pointer?
#include <stdio.h>
typedef void (func_type)(void);
func_type *func_ptr;
func_type func_obj;
int main()
{
printf("Size of func_obj: %zu\n", sizeof func_obj);
printf("Size of func_ptr: %zu\n", sizeof func_ptr);
return 0;
}
The code prints:
Size of func_obj: 1
Size of func_ptr: 8
These declarations
typedef void (func_type)(void);
func_type *func_ptr;
are similar to declarations like for example
typedef int T;
T *int_ptr;
So there is nothing wrong with the typedef that intrduces an alias for a function type.
Pay attention to that this typedef declaration
typedef void (func_type)(void);
is equivalent to
typedef void func_type(void);
This declaration
func_type func_obj;
declares a function with the name func_obj
of the type void( void )
.
Such a declaration allows for example to list functions in one line without repeating their parameter lists.
This statement
printf("Size of func_obj: %zu\n", sizeof func_obj);
is invalid according to the C Standard because you may not apply the sizeof
operator to a functon.
From the C Standard (6.5.3.4 The sizeof and alignof operators)
1 The sizeof operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member. The alignof operator shall not be applied to a function type or an incomplete type.
Some compilers however can have their own extensions that contradict the C Standard.