Thread: Point of function pointers

  1. #1
    Registered User
    Join Date
    Sep 2014
    Posts
    83

    Point of function pointers

    Hi all,

    I'm wondering about the point of pointers to functions. When is it used?
    I saw the below example. It doesn't make sense to me. I mean we can easily write code that does the same without having to use pointers. Thanks.

    Code:
    #include <stdio.h>
    
    
    int addInt(int a, int b);        // Adds 2 integers  
    int add5to4(int (*function_pointer)(int, int));
    
    int main(void)
    {
        int sum;
        int (*function_pointer)(int, int);
        
        function_pointer = &addInt;
        sum = (*function_pointer)(2, 3);
        printf("Sum: %d\n", sum);
        sum = function_pointer(5,6);   // Alternative way.    
        printf("Sum: %d\n", sum);
        
        sum = add5to4(*function_pointer);
        printf("Sum: %d\n", sum);
        
        return 0;
    }
    
    int addInt(int a, int b)
    {
        return a + b;
    }
    
    int add5to4(int (*function_pointer)(int, int))
    {
        return (*function_pointer)(5, 4);
    }

  2. #2
    Tweaking master Aslaville's Avatar
    Join Date
    Sep 2012
    Location
    Rogueport
    Posts
    528
    Function pointers are useful when you want to pass functions as arguments to other functions and more importantly when you may want to pass different functions which have the same prototype(depending on a particular use-case).

    For instance the signature of qsort is

    Code:
    void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*));
    In this case you can pass any function that accept two void * arguments and returns an integer as the fourth argument.
    Last edited by Aslaville; 09-27-2014 at 02:03 AM.

  3. #3
    Registered User
    Join Date
    Sep 2014
    Posts
    83
    Thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can someone point out my issues with pointers?
    By DyslexicDan in forum C Programming
    Replies: 8
    Last Post: 12-05-2011, 05:04 AM
  2. What is the point of pointers?
    By omnificient in forum C Programming
    Replies: 15
    Last Post: 12-15-2007, 06:09 PM
  3. Whats the point of pointers?
    By Goosie in forum C++ Programming
    Replies: 22
    Last Post: 06-22-2005, 05:38 PM
  4. wut is the point of pointers (no pun intended)
    By Geo-Fry in forum C++ Programming
    Replies: 2
    Last Post: 03-08-2003, 12:13 PM
  5. Pointers *Point?
    By bluehead in forum C++ Programming
    Replies: 1
    Last Post: 01-08-2002, 10:23 PM