Function Pointers
C is already so hard and why such function pointers???
They are interesting and they help you to get separateed from soydevs who use chatgpt and genAI to code. May the legacy of legacy programmers Rise!
int func(int x, int y) {
return x + y;
}
// Declaring a Function Pointer
int (*ptr_name) (int, int) = func;
When we write a fucntion like this, it is converted into machine code (binary boop boop beep) by the compiler at compile time. A fucntion ultimately is just an address in memory where there exists some code. So, Techinically, we can make and use function pointers for different purposes.
Suppose we do something like
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
bool is_even(int x){
return x % 2 == 0;
}
void print_conditional(int x[10], bool (*predicate) (int)) {
for (int i = 0; i < 10; i++) {
if (predicate(x[i])) {
printf("%d\n", x[i]);
}
}
}
int main() {
int x[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
print_conditional(x, is_even);
}
Gives Output
batman@batcave ~/C/c (master)> goku fp.c
2
4
6
8
10
batman@batcave ~/C/c (master)>
Heck with usability, This is cool that i can write k different predicate check functions, which can be passed into the print_conditional without changing the core logic. Write good test cases, or making very generic abstract functions… Do anything. Its C. See?