# pure - struct function pointer

## 你如何在C中傳遞一個函數作為參數? (4)

``````void func ( void (*f)(int) );
``````

``````void print ( int x ) {
printf("%d\n", x);
}
``````

``````func(print);
``````

``````for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
``````

``````void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
``````

``````#include <stdio.h>

void print();
void execute(void());

int main()
{
execute(print); // sends address of print
return 0;
}

void print()
{
printf("Hello!");
}

void execute(void f()) // receive address of print
{
f();
}
``````

``````#include <stdio.h>

void print();
void execute(void (*f)());

int main()
{
execute(&print); // sends address of print
return 0;
}

void print()
{
printf("Hello!");
}

void execute(void (*f)()) // receive address of print
{
f();
}
``````

``````std::function<bool (int)>
``````

``````// g++ test.cpp --std=c++11
#include <functional>

double Combiner(double a, double b, std::function<double (double,double)> func){
return func(a,b);
}

double Add(double a, double b){
return a+b;
}

double Mult(double a, double b){
return a*b;
}

int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
``````

``````// g++ test.cpp --std=c++11

template<class T>
double Combiner(double a, double b, T func){
return func(a,b);
}

double Add(double a, double b){
return a+b;
}

double Mult(double a, double b){
return a*b;
}

int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
``````

``````typedef void (*functiontype)();
``````

``````void dosomething() { }

functiontype func = &dosomething;
func();
``````

``````typedef int (*functiontype2)(char);
``````

``````int dosomethingwithchar(char a) { return 1; }

functiontype2 func2 = &dosomethingwithchar
int result = func2('a');
``````

``````boost::function<int (char a)> functiontype2;
``````