Skip to content

Commit

Permalink
Passing function as parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandrevicenzi committed Aug 18, 2014
1 parent 8868474 commit ba56a48
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions cpp/func.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#include <iostream>

using namespace std;

// Store your function in a variable.
// Function with no arguments and no return.
void (*func)() = 0;
// Function with two arguments and return.
int (*arg_func)(int, int) = 0;

void print()
{
cout << "Hooray" << endl;
}

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

// Passing function as argument.
void call_function(void (*f)())
{
f();
}

// Passing function with parameters as argument.
int call_arg_function(int (*f)(int, int))
{
return f(2, 2);
}

int main(int argc, char const *argv[])
{
func = print;
func(); // Print Hooray.
call_function(print); // Print Hooray.

arg_func = sum;
cout << arg_func(2, 2) << endl; // Print 4.
cout << call_arg_function(sum) << endl; // Print 4.

return 0;
}

0 comments on commit ba56a48

Please sign in to comment.