ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    CC-112
    Progress0 / 39 topics
    Topics
    1. Introduction to Problem Solving, Algorithms, Programming, and C Language2. Problem Solving, a brief review of Von-Neumann Architecture3. The C Programming Language, Pseudo-code, Concept of Variable4. Data types in Pseudo-code, The C Standard Library and Open Source5. Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6. Concept of Integer division, Flowchart and its notations7. Typical C Program Development Environment, Role of Compiler and Linker8. Test Driving C Application9. Introduction to C Programming: A Simple C Program: Printing Text, Adding Two Integer10. Memory Concepts, Arithmetic in C, Operators11. Decision Making: Equality and Relational Operators12. Structured Program Development: The if, if...else, while Nested Control Statements13. Program Control: for, switch, do...while, break, continue, Logical Operators14. Functions: Modularizing Program in C, Math Library Functions15. Function Definitions and Prototypes, Function-Call Stack and Stack Frames16. Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17. Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration18. Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays19. Passing Arrays to Function, Sorting and Searching Arrays20. Multidimensional and Variable Length Arrays21. Pointers: Pointer Definitions and Initialization, Pointer Operators22. Passing Arguments to Function by Reference, Using the const and sizeof Operator23. Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24. Function Pointers25. Characters and Strings: Strings and Characters, Character Handling Library26. String Functions, Library Functions27. Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf28. Structures: Defining Structures, Accessing Structure Member, Structures and Functions29. typedef, Unions30. Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants31. File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File32. Preprocessor: #include, #define, Conditional Compilation, #error and #pragma33. # and ## Operators, Predefined Symbolic Constants, Assertions34. Other Topics: Variable Length Argument List, Using Command Line Arguments35. Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36. Suffixes for Integer and Floating-Point Literals, Signal Handling37. Dynamic Memory Allocation: calloc and realloc, goto38. Advance Topics: Self-Referential Structures, Linked Lists39. Efficiency of Algorithms, Selection and Insertion Sort
    CC-112›Function Pointers
    Programming FundamentalsTopic 24 of 39

    Function Pointers

    7 minread
    1,168words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,168
      Code examples0
      DifficultyIntermediate