×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to pass function as an argument to a function

In this C program, we are going to implement a function that will have function as an argument in C. There are two user defined functions and we are passing function 1 as an argument to the function 2.
Submitted by IncludeHelp, on March 22, 2018

Problem statement

Given two integer values and we have to pass them to function 1, that will return the sum and then we have to pass function 1 as an argument to the function 2, which will print the sum in C.

Note: When, we will pass the fun_1() to the fun_2(), it will be treated as an integer values because fun_2() is taking an argument of integer type. So, first of all fun_1() will be executed and return the sum of the given parameters and sum will be passed to the fun_2() which will be processed.

Function Declarations

Consider the given functions,

1) function 1 (fun_1)

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

Function is taking two integer arguments and returning their sum.

2) function 2 (fun_2)

int fun_2(int temp)
{
    printf("\nThe value of temp is : %d",temp);
}

Function is taking an integer value and printing it.

Function Calling

Function calling seems to like ‘passing function to a function as an argument’

fun_2(fun_1(i,j));

Here, the returned vale of fun_1(i,j) will be supplied as an argument to the fun_1().

Program to pass function as an argument to a function in C

/*  
C program to pass function 1 as an argument
to a function 2
*/

#include <stdio.h>

// function 1
int fun_1(int a , int b)
{
    return (a+b);
}

// function 2
int fun_2(int temp)
{
    printf("\nThe value of temp is : %d",temp);
}

// main function
int main()
{
    // define some variables
    int i=5 , j=6;
    
    // calling the function fun_2 and Passing
    // fun_1 as an argument to it
    fun_2(fun_1(i,j));
    
    return 0;
}

Output

The value of temp is : 11

C User-defined Functions Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.