0
0
CHow-ToBeginner · 3 min read

How to Pass Function as Argument in C: Simple Guide

In C, you can pass a function as an argument by using a function pointer. This means you declare a pointer that points to a function's address and pass it to another function, which can then call the passed function.
📐

Syntax

To pass a function as an argument, declare a parameter as a function pointer with the same signature as the function you want to pass.

Example parts:

  • return_type (*pointer_name)(parameter_types): declares a function pointer.
  • function_name: the actual function you want to pass.
  • pointer_name(args): calling the function via the pointer.
c
#include <stdio.h>

void caller(void (*func)(int)) {
    func(5);
}

void callee(int x) {
    printf("Value: %d\n", x);
}
💻

Example

This example shows how to pass a function that prints a number to another function that calls it.

c
#include <stdio.h>

void printNumber(int n) {
    printf("Number is %d\n", n);
}

void execute(void (*func)(int), int value) {
    func(value);
}

int main() {
    execute(printNumber, 10);
    return 0;
}
Output
Number is 10
⚠️

Common Pitfalls

Common mistakes include:

  • Not matching the function pointer signature exactly with the function's signature.
  • Forgetting to use parentheses around the function pointer in the parameter list.
  • Trying to pass a function without using a pointer.

Always ensure the function pointer type matches the function you want to pass.

c
/* Wrong: missing parentheses around pointer */
void caller(void *func(int)) { /* incorrect */ }

/* Correct: parentheses around pointer */
void caller(void (*func)(int)) { /* correct */ }
📊

Quick Reference

Tips for passing functions as arguments in C:

  • Use return_type (*pointer_name)(parameters) to declare function pointers.
  • Pass the function name without parentheses to pass its address.
  • Call the function inside using pointer_name(args).
  • Ensure signatures match exactly.

Key Takeaways

Use function pointers to pass functions as arguments in C.
The function pointer's signature must match the function's signature exactly.
Pass the function name without parentheses to pass its address.
Call the passed function inside using the pointer with arguments.
Always use parentheses around the function pointer in parameter declarations.