3

How do I use a function before it gets declared?

I have 3 functions, each one of them has to interact with each other, but I can't find a way to make the earlier declared functions to interact with the later declared functions. Here's the code:

int f(int a){
    if (a==0){return 1;}
    if (a==1){return 2;}
    if (a==2){return 7;}
    return 2*f(a-1)+3*f(a-2)+3*f(a-3)+6*g(a-2)+2*g(a-3)+2*h(a-2);
}

int g(int b){
    if (b==0){return 0;}
    if (b==1){return 1;}
    return f(b-1)+g(b-1)+h(b-1);
}

int h(int c){
    if (c==0){return 0;}
    if (c==1){return 1;}
    return f(c-2)+g(c-1)+g(c-2);
}
user
  • 934
  • 6
  • 17
Ant
  • 55
  • 3

1 Answers1

6

A function only needs to know another function's name, its argument types and its return type to be able to call it. It doesn't need to be fully implemented at the point where you call it. Simply declare your functions first and implement them later.

// Declare before use
int g(int b);
int h(int c);

// Implement here
int f(int a){
    if (a==0){return 1;}
    if (a==1){return 2;}
    if (a==2){return 7;}
    return 2*f(a-1)+3*f(a-2)+3*f(a-3)+6*g(a-2)+2*g(a-3)+2*h(a-2);
}

int g(int b){
    if (b==0){return 0;}
    if (b==1){return 1;}
    return f(b-1)+g(b-1)+h(b-1);
}

int h(int c){
    if (c==0){return 0;}
    if (c==1){return 1;}
    return f(c-2)+g(c-1)+g(c-2);
}
user
  • 934
  • 6
  • 17
François Andrieux
  • 28,148
  • 6
  • 56
  • 87