Search code examples
cfunctionclangaliasfreestanding

Making a function to choose an interface depending on arguments


I want to make a function to choose another one in C, maybe this C-pseudo code can help a little to clarify what I want:

void set_method(const char *method)
{
    // Check if the method is serial_port
    if (strcmp(method, "serial_port") == 0)
    {
        // assign the alias "print" to serial_print
        // something like defing here a function like this:
        // print(const char *print) { serial_print(print); }

        print(const char *print) = serial_print(const char *message)
    } 
    else if (strcmp(method, "graphical_tty") == 0)
    {
        // The same that serial_port case but with graphical_tty_print
    } 
    else
    {
        // Error
    } 
} 

The goal is to assign an "alias" to a function if the condition is met, how can I do this?

I'm using a freestanding C implementation for this, compiled with clang.


Solution

  • It seems as you are looking for function pointers. See the following code, which introduces a type of function to call, a global pointer to a function of that type, and the code assigning an appropriate function according to your logic:

    typedef int (*PrintFunctionType)(const char*);
    
    int serial_print(const char *message) { printf("in serial: %s\n", message); return 0; }
    int tty_print(const char* message) { printf("in tty: %s\n", message); return 0; }
    
    
    PrintFunctionType print = serial_print;  // default
    
    void set_method(const char *method)
    {
        // Check if the method is serial_port
        if (strcmp(method, "serial_port") == 0)        {
            print  = serial_print;
        }
        else if (strcmp(method, "graphical_tty") == 0)        {
            print = tty_print;
        }
        else       {
            // Error
        }
    }
    
    int main() {
        print("Hello!");
        set_method("graphical_tty");
        print("Hello!");
    }
    
    //Output:
    //
    //in serial: Hello!
    //in tty: Hello!
    

    Hope it helps :-)