Function in parameter list of another function/subroutine

Hello everyone,
I am writing a main code which uses a subroutine which has some mathematical function in its argument list. Let's say the subroutine (call it
double Integrate(...,..,..)) does integration and that a mathematical function (e.g.f(x) = sin(x)) is in the argument list of subroutine declaration and definition. How to do that in C++? The function's value (f(x)) will be evaluated within subroutine so it seems I cannot define
f(x) as a variable with fixed value in the argument list. How to ascribe form of f(x) in this case? Should I do it in the main() by writing s'thing like

//......
main()
{
double result;
double f(double x);

f(x)=sin(x);

result = Integrate(f,...,...);

...//

It does seem very wrong to me to do this but if say I define another subroutine that calculates f(x)..

//...
double f(double x);

main()
{
double result;
double fs;
double x;

fs = f(x);

result = Integrate(fs,....)

//

then f(x) is evaluated in main instead of in subroutine Integrate

Any one can help on this? Thanks in advance.


steveurkel




You don't understand what a function is.
A function is (nearly. There's a merely semantical difference that's not relevant to this discussion) synonymous with subroutine. A subroutine is a piece of code that performs some operation based on data passed to it, and that can be executed from any other subroutine that knows it exists.
When a subroutine returns a value, it is similar to the concept of "function" found in mathematics: both give a result based on some value. However, where mathematical notation reads
f(x)=sin(x)
C/++ source reads
1
2
3
double f(double x){
    return sin(x);
}
(It could be said that the mathematical notation is a shorthand of this syntax.)


What you want to do can be done, but you will be limited by the number of parameters and you'll have to recompile if you need to change the function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
double integrate(                     //integrate() returns a double and takes:
    double(*f)(double,double,double), //a pointer to a function that takes three
                                      //doubles and returns a double;
    double x0,                        //a double;
    double x1){                       //and a double.

    //Integrate.
}

double f(double x,double y,double z){
    //return sin(x);
    //Function body here.
}

int main(){
    double s=integrate(&f,-10,10);
    return 0;
}
Last edited on
Topic archived. No new replies allowed.