• C

Question on function typedef?

I am looking at a Richard Stevens book to help with a program i am writing.
the code i was looking at contained this:
typedef  int  Myfunc(const char *, const struct stat *, int);
               /* function type that's called for each filename */

what is this for?  i have not seen this before. is it just to simplify
passing a function and args to another function?
there is an function in the code myfunc().
i can post more of the code if needed.

Who is Participating?
BTW, "qsort()" is a nice example for this:

The "normal" declaration is

void qsort( void *base, size_t num, size_t width, int (__cdecl *compare )(const void *elem1, const void *elem2 ) );

Using the "typedef", you could rewrite it as

typedef int (__cdecl *COMPARE_PROC )(const void *elem1, const void *elem2 );

void qsort( void *base, size_t num, size_t width,  COMPARE_PROC compare);

where "COMPARE_PROC" is a type that represents a pointer to a function which takes the above argument list and returns an "int"
This statement is creating a "function pointer type" and basically makes code more "readable".

neptunaAuthor Commented:
so basically it is saving us some typing ?
>>so basically it is saving us some typing ?

Yes. And it makes using function pointers more typesafe - just imagine the above "qsort()" would be called using a function with a different signature, e.g.

int __cdecl MyCompare(const int elem1, const int elem2 );

The result would be a crash...
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.