TalentJR

⚙️ C programming basics · Class 10 · Lesson 9 of 18 · Free

Function Pointers in C – Callbacks, qsort and Menu Tables

⏱ About 35 minutes · ▶ run real C here — nothing to install · no sign-in

In this lesson you will

  • Declare a function pointer, point it at a function and call it
  • Pass functions as callbacks, including the compare function for qsort
  • Build tables of function pointers, made easier with typedef

A shop's billing program applies a different discount on Diwali, on Sundays and for members. Instead of a long if-else chain everywhere, you can store "which rule to use" in a variable. In C, a variable that stores a function is a function pointer.

What is a function pointer in C?

Functions also live in memory, so they have addresses too. A function pointer stores the address of a function, so you can call "whichever function it points to".

int (*op)(int, int); means: op is a pointer to a function that takes two ints and returns an int. The brackets around *op are required.

A function's name alone, like add, gives its address. You call through the pointer just like a normal function: op(5, 3).

Try it: write int mul(int a, int b) and point op at it.

⚙️ C — you can edit this code
Output
op(50, 30) = 80
op(50, 30) = 20

💡 You may also write op = &add; and (*op)(50, 30). Both styles mean the same thing.

What is a callback function in C?

A callback is a function you pass to another function, so it can call it back later. The receiving function does the common work (here: loop over all marks). The callback decides the special part (here: how to change one mark).

apply_all does not know about grace marks or rounding. That is the point: one loop, many behaviours.

Try it: write a callback int cap100(int m) that turns anything above 100 into 100, and apply it too.

⚙️ C — you can edit this code
Output
34 47 88 33 64 
35 45 90 35 65 

💡 cond ? a : b is a short if-else: it gives a when cond is true, else b.

How do you use qsort with a compare function in C?

qsort from <stdlib.h> sorts any array: ints, strings or structs. It cannot know how to compare YOUR items, so you pass a compare function.

The compare function gets two const void * pointers ("pointer to anything"). You convert them to your real type. Return a negative number if the first should come first, positive if the second should, and 0 if they are equal.

Here students are sorted by marks, highest first, and by name when marks are equal.

Try it: change the compare function to sort by name only.

⚙️ C — you can edit this code
Output
1. Dev    95
2. Aman   92
3. Riya   88
4. Zoya   88
5. Kabir  71

💡 y - x is safe here because marks are small. For huge numbers, compare with < and > instead to avoid overflow.

How do you make an array of function pointers in C?

You can keep many function pointers in an array. Then a number, like a menu choice, picks the function directly: ops[choice](a, b). No long switch is needed.

Always check that the index is inside the array before calling. Calling through a bad pointer crashes the program.

Try it: change the inputs to 3 and 7 6, or add a fifth operation, modulo.

⚙️ C — you can edit this code
Output
0 Add 1 Subtract 2 Multiply 3 Divide: 2
Two numbers: 12 8
Multiply: 96

How does typedef make function pointers easier in C?

int (*ops[4])(int, int) is hard to read. typedef gives the pointer type a name: typedef double (*Discount)(double); Now Discount is a type, like int.

Here a struct pairs a rule's name with its function, and the shop looks up the rule by name with strcmp. Adding a new offer means writing one function and adding one row.

Try it: add a rule "festival" that gives 15 % off, and use it for the bill.

⚙️ C — you can edit this code
Output
Rule sunday: Rs 640.00 -> Rs 590.00
Member price: Rs 608.00

🤔 Predict the output

Think like C: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

#include <stdio.h>

int twice(int x) { return 2 * x; }
int square(int x) { return x * x; }

int main(void) {
    int (*f)(int) = twice;
    int a = f(3);
    f = square;
    printf("%d %d\n", a, f(3));
    return 0;
}

Question 2. What does this print?

#include <stdio.h>

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

int main(void) {
    int (*ops[2])(int, int) = {add, mul};
    printf("%d\n", ops[1](ops[0](2, 3), 4));
    return 0;
}

Question 3. What does this print?

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

int cmp(const void *a, const void *b) {
    return *(const int *) b - *(const int *) a;
}

int main(void) {
    int runs[] = {34, 102, 7, 56};
    qsort(runs, 4, sizeof(int), cmp);
    printf("%d %d\n", runs[0], runs[3]);
    return 0;
}

🧩 Your challenge

Write int count_if(const int a[], int n, int (*test)(int)) that counts how many items pass the test. Write two tests: is_pass (33 or more) and is_distinction (75 or more). Use them on the marks list. Expected output: Passed: 5 Distinction: 4

Expected output :
Items: 7
Passed: 5
Distinction: 4
⚙️ C — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

#include <stdio.h>

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

int main(void) {
    int *op(int, int) = add;
    printf("%d\n", op(2, 3));
    return 0;
}

Line 6: error: illegal initializer (only variables can be initialized)

✅ Right

#include <stdio.h>

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

int main(void) {
    int (*op)(int, int) = add;
    printf("%d\n", op(2, 3));
    return 0;
}

Without brackets, int *op(int, int) declares a FUNCTION that returns int *, not a pointer. Write int (*op)(int, int).

❌ Wrong

#include <stdio.h>

double half(double x) { return x / 2; }

int main(void) {
    int (*f)(int) = half;
    printf("%d\n", f(10));
    return 0;
}

Line 6: error: incompatible function pointer types initializing 'int (*)(int)' with an expression of type 'double (double)' [-Wincompatible-function-pointer-ty…

✅ Right

#include <stdio.h>

double half(double x) { return x / 2; }

int main(void) {
    double (*f)(double) = half;
    printf("%.1f\n", f(10));
    return 0;
}

The pointer's type must match the function exactly: same return type and same parameter types.

❌ Wrong

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

int highest_first(const void *a, const void *b) {
    return *(const int *) a - *(const int *) b;
}

int main(void) {
    int marks[] = {67, 95, 81};
    qsort(marks, 3, sizeof(int), highest_first);
    printf("Topper: %d\n", marks[0]);
    return 0;
}

Compiles and runs, but prints: Topper: 67 ⏎

✅ Right

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

int highest_first(const void *a, const void *b) {
    return *(const int *) b - *(const int *) a;
}

int main(void) {
    int marks[] = {67, 95, 81};
    qsort(marks, 3, sizeof(int), highest_first);
    printf("Topper: %d\n", marks[0]);
    return 0;
}

a - b sorts smallest first. For highest first, return b - a (or flip the < and > tests).

📌 Remember

  • A function pointer stores a function's address: int (*op)(int, int) = add;
  • Call through it like a normal function: op(2, 3).
  • Callbacks let one general function (like apply_all or qsort) use your special behaviour.
  • qsort's compare function returns negative, 0 or positive to set the order.
  • Arrays and structs of function pointers make menus and rule tables; typedef keeps them readable.

Finished the quiz and the challenge?

Questions students ask

What is the use of function pointers in C?

They let you choose behaviour at run time: callbacks, sorting with qsort, menu tables and plug-in rules. Event handlers in operating systems and games often work this way.

Why are there brackets in int (*f)(int)?

Without them, int *f(int) would mean "a function f that returns an int pointer". The brackets make * belong to f, so f is a pointer to a function.

Is a function pointer the same as a callback?

A callback is the idea: a function you hand to other code to call later. In C, you hand it over using a function pointer.

Can a C function return a function pointer?

Yes. With a typedef it stays readable: Discount pick_rule(int day); returns one of your rule functions. Without typedef the syntax is very hard to read, so typedef is the usual choice.