Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining function pointer in C?

  1. 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?

  1. 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
like image 585
mrn Avatar asked Sep 12 '26 16:09

mrn


1 Answers

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.

like image 132
Vlad from Moscow Avatar answered Sep 14 '26 09:09

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!