Is it possible to swap C functions?

后端 未结 5 440
难免孤独
难免孤独 2021-01-06 08:09

Looking to see if anyone knows if its possible to swap C functions...?

 void swap2(int(*a)(int), int(*b)(int)) {
   int(*temp)(int) = a;
   *a = *b;
   *b =          


        
5条回答
  •  囚心锁ツ
    2021-01-06 08:56

    If you use the function pointers like below, it is yes

    typedef int (*func_pt)(int);
    
    func_pt a, b;
    
    void swap(func_pt * a, func_pt * b)
    {
        func_pt tmp = *b;
        *b = *a;
        *a = tmp;
    }
    
    swap(&a, &b);
    

    Or you use it as this, I think it is no:

    int test1(int a)
    {
        return a;
    }
    
    int test2(int b)
    {
        return b;
    }
    
    swap(&test1, &test2);
    

    Complete compiling working program

    #include 
    #include 
    
    typedef int (* func_pt)(int);
    
    func_pt a, b;
    
    int test1(int a)
    {
        printf("test1\n");
        return 1;
    }
    
    int test2(int a)
    {
        printf("test2\n");
        return 2;
    }
    
    void swap(func_pt * a, func_pt * b)
    {
        func_pt tmp = *b;
    
        *b = *a;
        *a = tmp;
    }
    
    int main(void)
    {
        a = &test1;
        b = &test2;
    
        printf("before\n");
        a(1);
        b(1);
    
        swap(&a, &b);
    
        printf("after\n");
        a(1);
        b(2);
    
        return 0;
    
    }
    

    Output:

    before
    test1
    test2
    after
    test2
    test1
    

    Some people do not try it by themselves, just say it absurd.So I give you a example.

提交回复
热议问题