0

In c, we have to define all the functions globally. while studying function pointer i got some program where programmer passes function name as parameter to other function. so why we need to pass function to other function if they all are globally defined?

here i am giving small sample program :

#include<stdio.h>

void bsort(int arr[],int n,int (*compare)(int,int))    //bubble sort
{
    int i,j,temp;
    for(i=0;i<n;i++){
        for(j=0;j<n-i-1;j++){
            if(compare(arr[j],arr[j+1]) > 0 ){
                temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}

int compare(int a,int b)
{
    if(a > b) return 1;
    return -1;
}

void main()
{
    int i;
    int arr[5]={6,5,1,9,2};
    bsort(arr,5,compare);

    for(i=0;i<5;i++)
    printf("%d ",arr[i]);   
}

in this code, if we remove 3rd argument in definition and calling part of bsort function then also our program will give us same output.so for function pointer this program doesn't make sense. can you please do some modification in this code and make it good example for function pointer.

Thanks.

Akash Patel
  • 27
  • 1
  • 8
  • 1
    `void func()` does not need to be global. It only needs to be seen by `main()`. It could be static in same .c file as `main()`. – chux - Reinstate Monica Oct 16 '14 at 17:16
  • You must pass a comparison function for the comparison of the elements of the case functions such as `bsearch` and `qsort` can not be assumed in advance. – BLUEPIXY Oct 16 '14 at 17:17
  • 2
    I'm not sure what you're asking. The point of a function pointer is to change the behavior of a particular function at run time. – Alex Reinking Oct 16 '14 at 17:17
  • 1
    Just because they're globally defined in your example, does not mean that this will always be the case. – AntonH Oct 16 '14 at 17:18
  • 1
    possible duplicate of [What is the point of function pointers?](http://stackoverflow.com/questions/2592137/what-is-the-point-of-function-pointers) – Roney Michael Oct 16 '14 at 17:22
  • If possible please give small code, rather than qsort. because i tried to find my answer on many sites and they all just explaining qsort. but i cant got their point of view. they also uses word callback. what is it? – Akash Patel Oct 16 '14 at 17:36
  • If you cannot understand function pointers and callbacks, what is the point of giving code? You won't understand it. – Martin James Oct 16 '14 at 18:37
  • What @AntonH says. Suppose you need to use an async OS or library API that needs to call one of your functions later? – Martin James Oct 16 '14 at 18:45
  • i know function pointer. but can't understand its application. – Akash Patel Oct 16 '14 at 18:49
  • @AkashPatel Lots of examples if you think about it. For example, game AI. A creature will behave a certain way, ie, it received pointer to behaviour function. Depending on events (eg., creature gets attacked, or hears a noise), you can apply a new behavioural pattern to the creature by changing the pointer to function. So no `if ... else if ...` or `switch ... case`. That's just one example. You'll have to find others yourself for your C programming blog :) – AntonH Oct 16 '14 at 18:52

4 Answers4

1

Your code does not actual need passing functions as parameters. But your example is rather didactic to make you understand how function pointers work.

However it's important to understand them as they might become very useful especially when dealing with libraries loaded at runtime. There are tons of examples where function pointers are really a good tool.

Here's one:

#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>

double doOperation(double arg, double (*func)(double))
{
    return (*func)(arg);
}

int main(int argc, char **argv) {
    void *handle;
    double (*cosine)(double);
    char *error;

    handle = dlopen ("/lib/libm.so.6", RTLD_LAZY);
    if (!handle) {
        fputs (dlerror(), stderr);
        exit(1);
    }

    cosine = dlsym(handle, "cos");
    if ((error = dlerror()) != NULL)  {
        fputs(error, stderr);
        exit(1);
    }

    printf ("%f\n", doOperation(2.0, cosine);
    dlclose(handle);
}

You open a library, search for the cosine function, and then pass it as an argument to doOperation.

You can also look here for more info.

VAndrei
  • 5,420
  • 18
  • 43
0

Function pointers are used when you might need to change the behavior of your function call depending on some dynamic requirement.

This page sums it up short and sweet:

A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior. For instance, every time you need a particular behavior such as drawing a line, instead of writing out a bunch of code, all you need to do is call the function. But sometimes you would like to choose different behaviors at different times in essentially the same piece of code.

A few excellent examples are available there are well.

Roney Michael
  • 3,964
  • 5
  • 30
  • 45
  • i am still not getting the point. Can you please give small code for this. or correct my code by making it perfect example for my question. thanks... – Akash Patel Oct 16 '14 at 17:46
  • 1
    Decaying rapidly towards a 'gimme teh codez' copy/paste homework answer. – Martin James Oct 16 '14 at 18:39
  • 1
    Did you even bother following the links provided, either in this response or in the comments to the question? – AntonH Oct 16 '14 at 19:40
0

You pass a function [pointer] to another function because you want to dynamically direct which function the receiver calls. Or more precisely, because the receiver function is built to allow you to do so, thereby requiring you to do so. The pointed-to function does not need to be available at the time the receiver is compiled.

The comparison function required as a qsort() argument is the prototypical example.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
0

Q: Why pass a function to another function?

Without re-writing bsort(), code can sort more than 1 way by only changing the compare function.

#include <stdio.h>
#include <stdarg.h>
int compare_up(int a,int b) {
    if(a > b) return 1;
    return -1;
}

int compare_down(int a,int b) {
    if(a < b) return 1; // reverse the compare
    return -1;
}

int compare_random(int a,int b) {
   return rand() & 1;  // mix them up
}

int main(void) {
    int i;
    int arr[5]={6,5,1,9,2};

    bsort(arr,5,compare_up);
    for(i=0;i<5;i++) printf("%d ",arr[i]); puts("");

    bsort(arr,5,compare_down);
    for(i=0;i<5;i++) printf("%d ",arr[i]); puts("");

    bsort(arr,5,compare_random);
    for(i=0;i<5;i++) printf("%d ",arr[i]); puts("");

    return 0;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256