Search code examples
cfunction-pointersdefinition

What is the meaning in C when a function is in another function's name (not in the arguments)?


Why is "void (*parse(char *op))(int, int)" written like this? (main added to give use case), it gets called from a pointer "fun" with argv[2] without the ints (line 18)... and then again as "fun" with the ints (line 21)?

void    (*parse(char *op))(int, int)
{
    if (!strcmp(op, "+"))
        return(other stuff...); 
    else
        return (0);
}
int     main(int argc, char *argv[]){
    int a;
    int b;
    void    (*fun)(int, int);

    if (argc == 4){
        a = atoi(argv[1]);
        fun = parse(argv[2]);
        b = atoi(argv[3]);
        if (fun)
            fun(a, b);
        else
            return(0);
    }
    return(0);
}

How does it technically work, and it is just a showoff with a simpler way to write it or is this the only correct grammar?


Solution

  • parse() is a function that returns a function pointer. You can use typedef with the type of the returned function to make it look a lot nicer, though:

    #include <string.h>
    #include <stdlib.h>
    
    // parser_func describes a function that takes two ints and returns nothing
    typedef void (*parser_func)(int, int);
    
    // Like this one.
    void somefunc(int a, int b) {}
    
    // And parse() is a function that takes a char* and returns a
    // pointer to a function that matches parser_func.
    parser_func parse(char *op) {
      if (!strcmp(op, "+"))
        return somefunc;
      else
        return NULL;
    }
    
    int main(int argc, char *argv[]) {
      int a;
      int b;
      parser_func fun; // Function pointer
    
      if (argc == 4) {
        a = atoi(argv[1]);
        fun = parse(argv[2]); // Assign a function to fun
        b = atoi(argv[3]);
        if (fun) {
          fun(a, b); // And call it if it's not null
        }
      }
      return 0;
    }