पाठ 15 / 38

Function Pointers और Callbacks

Function pointers से functions को रखें और पास करें ताकि callbacks और qsort comparators जैसा लचीला code लिखा जा सके।

Function pointer declare करना

Function pointer किसी function का address रखता है। Declaration में function का return type और parameter types दोहराए जाते हैं।

int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }

int apply(int (*op)(int, int), int x, int y) {
    return op(x, y);   // call through the pointer
}

int main(void) {
    printf("%d %d\n", apply(add, 3, 4), apply(mul, 3, 4));   // 7 12
    return 0;
}

qsort के साथ callbacks

Standard qsort तुलना function लेता है, इसलिए एक routine किसी भी type को sort करता है।

#include <stdlib.h>

int cmp_int(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);
}

int nums[] = {5, 2, 9, 1};
qsort(nums, 4, sizeof(int), cmp_int);

Function pointer types को पठनीय रखने के लिए typedef उपयोग करें, जैसे typedef int (*BinOp)(int, int);।

त्वरित जाँच

त्वरित जाँच: Function pointer क्या रखता है?

  • The address of a function
  • The return value of a function
  • A copy of the function body
  • The number of arguments
Answer

The address of a function — आप उसी address के माध्यम से function call करते हैं।