ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-112Function Pointers
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-112

    Programming Fundamentals

    Progress0 / 39 done
    Topics39
    1Introduction to Problem Solving, Algorithms, Programming, and C Language2Problem Solving, a brief review of Von-Neumann Architecture3The C Programming Language, Pseudo-code, Concept of Variable4Data types in Pseudo-code, The C Standard Library and Open Source5Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6Concept of Integer division, Flowchart and its notations7Typical C Program Development Environment, Role of Compiler and Linker8Test Driving C Application
    9A Simple C Program: Printing Text, Adding Two Integer10Memory Concepts, Arithmetic in C, Operators
    11Equality and Relational Operators
    12The if, if...else, while Nested Control Statements
    13for, switch, do...while, break, continue, Logical Operators
    14Modularizing Program in C, Math Library Functions15Function Definitions and Prototypes, Function-Call Stack and Stack Frames16Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    18Defining Arrays, Character Arrays, Static and Automatic Local Arrays19Passing Arrays to Function, Sorting and Searching Arrays20Multidimensional and Variable Length Arrays
    21Pointer Definitions and Initialization, Pointer Operators22Passing Arguments to Function by Reference, Using the const and sizeof Operator23Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24Function Pointers
    25Strings and Characters, Character Handling Library26String Functions, Library Functions
    27Streams, Formatted Output with printf, Formatted Input with scanf
    28Defining Structures, Accessing Structure Member, Structures and Functions29typedef, Unions
    30Bitwise Operators, Bit Fields, Enumeration Constants
    31Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    32#include, #define, Conditional Compilation, #error and #pragma33# and ## Operators, Predefined Symbolic Constants, Assertions
    34Variable Length Argument List, Using Command Line Arguments35Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36Suffixes for Integer and Floating-Point Literals, Signal Handling
    37calloc and realloc, goto
    38Self-Referential Structures, Linked Lists39Efficiency of Algorithms, Selection and Insertion Sort
    7 min read
    Topic 24 of 39
    Topic Study Note Illustration
    24

    Function Pointers

    A function pointer in C is a pointer that points to a function instead of a data value. It allows you to store the address of a...

    Function Pointers in C

    A function pointer in C is a pointer that points to a function instead of a data value. It allows you to store the address of a function in a pointer variable and invoke the function via the pointer. Function pointers are particularly useful for implementing callback functions, event-driven programming, or when you need to select between different functions at runtime.

    Let’s dive into function pointers in detail, including their syntax, use cases, and examples.


    1. Declaring and Initializing Function Pointers

    To declare a function pointer, you need to specify the function signature that the pointer will point to. The syntax for declaring a function pointer looks like this:

    return_type (*pointer_name)(parameter_types);
    

    Where:

    • return_type is the return type of the function.
    • pointer_name is the name of the pointer.
    • parameter_types are the types of the parameters that the function takes.

    Example: Declaring a Function Pointer

    Consider a function that adds two integers:

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

    To declare a pointer to this function:

    int (*ptr)(int, int);
    

    This declares ptr as a pointer to a function that takes two int parameters and returns an int. Now, you can assign the address of the add function to ptr:

    ptr = add;
    

    2. Using Function Pointers

    Once a function pointer is initialized, you can use it to call the function it points to. The syntax for calling a function through a function pointer is:

    (*ptr)(arg1, arg2);
    

    Alternatively, you can use the simpler form:

    ptr(arg1, arg2);
    

    Example: Using a Function Pointer

    #include <stdio.h>
    
    // Function declaration
    int add(int a, int b) {
        return a + b;
    }
    
    int main() {
        // Declare a function pointer
        int (*ptr)(int, int);
        
        // Point the function pointer to the add function
        ptr = add;
    
        // Call the function through the pointer
        int result = ptr(5, 3);  // Equivalent to add(5, 3)
    
        // Output the result
        printf("Result: %d\n", result);
    
        return 0;
    }
    

    Explanation:

    • The function pointer ptr is assigned the address of the add function.
    • We call ptr(5, 3), which is equivalent to add(5, 3).
    • The result is printed, showing 8.

    Output:

    Result: 8
    

    3. Function Pointers with Multiple Functions

    You can use function pointers to choose between multiple functions dynamically, allowing for greater flexibility and modularity in your code.

    Example: Using Function Pointers to Select a Function

    #include <stdio.h>
    
    // Function declarations
    int add(int a, int b) {
        return a + b;
    }
    
    int multiply(int a, int b) {
        return a * b;
    }
    
    int main() {
        // Declare a function pointer
        int (*operation)(int, int);
        
        // Assign the function pointer to 'add'
        operation = add;
        printf("Addition: %d\n", operation(5, 3));  // Calls add
    
        // Change the function pointer to 'multiply'
        operation = multiply;
        printf("Multiplication: %d\n", operation(5, 3));  // Calls multiply
    
        return 0;
    }
    

    Explanation:

    • The function pointer operation is first assigned to add, and then the add function is called.
    • Later, the pointer is reassigned to multiply, and the multiply function is called.

    Output:

    Addition: 8
    Multiplication: 15
    

    In this example, the function that gets called is determined by which function the operation pointer is pointing to.

    4. Function Pointers as Arguments (Callbacks)

    Function pointers are often used as callback functions. A callback is a function that is passed as an argument to another function and is invoked within that function.

    Example: Passing a Function Pointer as an Argument

    #include <stdio.h>
    
    // Function declarations
    int add(int a, int b) {
        return a + b;
    }
    
    int multiply(int a, int b) {
        return a * b;
    }
    
    // Function that takes a function pointer as a parameter
    void performOperation(int a, int b, int (*operation)(int, int)) {
        int result = operation(a, b);  // Call the function via pointer
        printf("Result: %d\n", result);
    }
    
    int main() {
        // Call performOperation with add
        performOperation(5, 3, add);  // Addition
        
        // Call performOperation with multiply
        performOperation(5, 3, multiply);  // Multiplication
        
        return 0;
    }
    

    Explanation:

    • performOperation is a function that accepts two integers and a function pointer operation as parameters.
    • We pass the add and multiply functions as arguments to performOperation, which then calls the appropriate function through the pointer.

    Output:

    Result: 8
    Result: 15
    

    This approach is useful when you need to provide flexibility to a function by allowing it to perform different operations based on the function pointer passed to it.

    5. Array of Function Pointers

    You can store multiple function pointers in an array, which is useful when you need to handle multiple functions in a structured way, such as implementing a simple menu-driven program or selecting functions dynamically.

    Example: Array of Function Pointers

    #include <stdio.h>
    
    // Function declarations
    int add(int a, int b) {
        return a + b;
    }
    
    int subtract(int a, int b) {
        return a - b;
    }
    
    int multiply(int a, int b) {
        return a * b;
    }
    
    int divide(int a, int b) {
        return a / b;
    }
    
    int main() {
        // Array of function pointers
        int (*operations[4])(int, int) = {add, subtract, multiply, divide};
        
        int a = 10, b = 5;
    
        // Perform all operations using the array of function pointers
        printf("Addition: %d\n", operations[0](a, b));
        printf("Subtraction: %d\n", operations[1](a, b));
        printf("Multiplication: %d\n", operations[2](a, b));
        printf("Division: %d\n", operations[3](a, b));
    
        return 0;
    }
    

    Explanation:

    • The array operations stores function pointers to four different functions: add, subtract, multiply, and divide.
    • Each function is called using its corresponding index in the array, passing a and b as arguments.

    Output:

    Addition: 15
    Subtraction: 5
    Multiplication: 50
    Division: 2
    

    In this example, you can easily add more operations to the array, and the code remains flexible and modular.


    6. Summary of Key Concepts

    • Function Pointers: Function pointers store the address of a function, allowing you to call the function indirectly.

    • Calling Functions via Pointers: You can invoke a function through its pointer using the (*pointer)(args) syntax or the simpler pointer(args).

    • Callbacks: Function pointers allow you to pass functions as arguments, enabling callback mechanisms where one function calls another function dynamically.

    • Arrays of Function Pointers: You can create arrays of function pointers to manage and call multiple functions in a structured way.

    Function pointers are a powerful feature in C that enable dynamic function calls, callbacks, and modular design. They are widely used in applications like event-driven programming, table-driven algorithms, and managing multiple functions in a flexible and extensible manner.

    ← Previous topic 23
    Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers
    Next topic 25 →
    Characters and Strings: Strings and Characters, Character Handling Library

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.2kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals