-1

Consider functions A, B and C.

void A(){
  int arg;
  B(arg);
}

void B(int& arg){
  C(arg)
}    

void C(int& arg){
  arg = 10;
}

I want value of my argument to be set by function C. This code gives an error. The order of the function calls has to be A calls B, which calls C. How to do this?

Vishal
  • 989
  • 2
  • 11
  • 19

3 Answers3

4

This should work, but you would have to write it that way (reorder the functions definitions):

void C(int& arg){
  arg = 10;
}

void B(int& arg){
  C(arg);
}    

void A(){
  int arg;
  B(arg);
}

Or to forward declare the functions before:

void B(int&);
void C(int&);

void A(){
  int arg;
  B(arg);
}

void B(int& arg){
  C(arg);
}    

void C(int& arg){
  arg = 10;
}

This way, A() knows of B() which knows of C().

ereOn
  • 53,676
  • 39
  • 161
  • 238
0

Reorder the functions in the source: C B A not A B C.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
0

Add prototype before your A() function. In your code, during compilation of A(), compiler have no idea about B(); So by function prototype you are telling compiler about it. And similarly for C()

void B(int&); 
void C(int&);

void A(){
    int arg;
    B(arg);
}

void B(int& arg){
    C(arg);
}    

void C(int& arg){
    arg = 10;
}

int main() {
    int a=20;
    A();
    return 0;
}
Digital_Reality
  • 4,488
  • 1
  • 29
  • 31