- Recently I came across a surprising way of defining a function pointer in C:
typedef void (func_type)(void);
func_type *func_ptr;
Is this a correct way of defining a function pointer?
- If we define func_obj as below, what is the type of this object and what this object can be used for?
#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
are similar to declarations like for example
So there is nothing wrong with the typedef that intrduces an alias for a function type.
Pay attention to that this typedef declaration
is equivalent to
This declaration
declares a function with the name
func_objof the typevoid( void ).Such a declaration allows for example to list functions in one line without repeating their parameter lists.
This statement
is invalid according to the C Standard because you may not apply the
sizeofoperator to a functon.From the C Standard (6.5.3.4 The sizeof and alignof operators)
Some compilers however can have their own extensions that contradict the C Standard.