Search code examples
cfunctiontypeof

how to use typeof of function to create another function with the same type


for example:

int f(int a, int b)
{
    return a + b;
}

typeof(f) f2
{
    return -f(a, b);
}

Is something like this possible in C?

Edit: The reason I'm asking this is I'm trying to do something like:

#define MAKE_NEGATION_OF(function) \
typeof(function) function##_negated { \
    return -function(a, b); \
}

Solution

  • I want use a macro to generate a function with the same type, but different return.

    Note that your two examples (used to) differ (before the question was edited).

    Given the previous typeof example, you could instead write a macro that generates functions with the same signature, differing only by key tokens:

    #include <stdio.h>
    
    #define DEFINE_BINARY_OPERATION(name, op) \
        int name(int a, int b) { \
            return a op b; \
        }
    
    DEFINE_BINARY_OPERATION(add, +)
    DEFINE_BINARY_OPERATION(subtract, -)
    
    int main(void)
    {
        printf("%d\n", add(5, 6));
        printf("%d\n", subtract(5, 6));
    }
    
    11
    -1
    

    Given the macro example, there is no need for another function, just negate the function call in a macro wrapper.

    #include <stdio.h>
    
    #define add_negated(...) (-add(__VA_ARGS__))
    
    int add(int a, int b)
    {
        return a + b;
    }
    
    int main(void)
    {
        printf("%d\n", add(5, 6));
        printf("%d\n", add_negated(5, 6));
    }
    
    11
    -11
    

    If you need a function pointer, then this is an extremely rigid combination of both ideas, which does not scale well at all. If your actual use case is non-trivial, you should probably just write the functions and their signatures by hand.

    #include <stdio.h>
    
    #define DEFINE_BINARY_EXPRESSION(name, expr) \
        int name(int a, int b) { \
            return expr; \
        }
    #define NEGATE_BINARY_EXPRESSION(name) \
        DEFINE_BINARY_EXPRESSION(name##_negated, -name(a, b))
    
    DEFINE_BINARY_EXPRESSION(add, a + b)
    NEGATE_BINARY_EXPRESSION(add)
    
    DEFINE_BINARY_EXPRESSION(subtract, a - b)
    NEGATE_BINARY_EXPRESSION(subtract)
    
    int main(void)
    {
        printf("%d\n", add(5, 6));
        printf("%d\n", add_negated(5, 6));
    
        printf("%d\n", subtract(5, 6));
        printf("%d\n", subtract_negated(5, 6));
    }
    
    11
    -11
    -1
    1