Explain typedef for function used in qsort library

前端 未结 3 1530
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 19:27

I am using qsort library function to sort an array of structure elements, while searching on the Internet I found a resource: INFO: Sorting Structures with the C qsort() Functio

相关标签:
3条回答
  • 2021-01-22 19:46

    Syntax:

    typedef  int (*compfn)  (const void*, const void*);
      ^      ^       ^            ^          ^
      | return type  |               arguments type
      |             new type name 
      defining new type
    

    compfn is a new user defined type defined by typedef keyword,

    So, you have exactly typedefded int (*)(const void*, const void*); to comfn using the syntax I described above.

    A declaration:

     compfn  fun; // same as: int (*fun)  (const void*, const void*);
    

    means fun is a function pointer that takes two arguments of const void* types and returns int.

    Suppose you have a function like:

    int xyz  (const void*, const void*);    
    

    then you can assign xyz address to fun.

    fun = &xyz; 
    

    At calling qsort():

    In expression (compfn)compare, you are typecasting a function compare to (compfn) type function.

    A doubt:

    shouldn't the call be (*compfn).

    No, its type name not function name.

    Note: if you just writing int (*compfn) (const void*, const void*); without typedef then comfn will be a pointer to a function that returns int and take two arguments of type const void*

    0 讨论(0)
  • 2021-01-22 19:57

    The typedef declaration creates an alias for a specific type. This means it can be used as any other type in declarations and definitions.

    So if you have e.g.

    typedef int (*compfn)(const void*, const void*);
    

    Then you can declare a variable or argument using only compfn instead of the whole function pointer declaration. E.g. these two declarations are equal:

    compfn function_pointer_1;
    int (*function_pointer_2)(const void*, const void*);
    

    Both creates a function pointer variable, and the only difference is the name of the variable name.

    Using typedef is common when you have long and/or complicated declarations, to easy both your writing of such declarations and to make it easier to read.

    0 讨论(0)
  • 2021-01-22 20:03

    It is a type of a function pointer. The function which is being pointed to returns int and accepts two const void* parameters.

    0 讨论(0)
提交回复
热议问题