C ++ Call function not yet defined

I have this code. How to do this without creating an error?

int function1() {
    if (somethingtrue) {
        function2();
    }
}

int function2() {
    //do stuff
    function1();
}
+4
source share
7 answers

Just put this above your functions:

int function1();
int function2();

But do not create an endless loop! With these two lines, you tell the compiler that function1and function2will be identified in the future. In large projects, you will use header files. There you do the same, but you can use functions in multiple files.

And also do not forget the return statement. I think your sample code was just a demo, but I just want to mention it.

++ . : fooobar.com/questions/483/...

+2

. , , , , .

int function2();  // this lets the compiler know that that function is going to exist

int function1() {
    if (somethingtrue) {
        function2(); // now the compiler know what this is
    }
}

int function2() { // this tells the compiler what it has to do now when it runs function2()
    //do stuff
    function1();
}
+8

. , , . , .

int function2();

int function1() {
    if (somethingtrue) {
        function2();
    }
}

int function2() {
    //do stuff
    function1();
}
+3

, .

int function2();

int function1() {
    if (somethingtrue) {
        function2();
    }
}

int function2() {
    //do stuff
    function1(); //beware of double recursion.
}
+1
int function2();

int function1() {
    if (somethingtrue) {
        function2();
    }
}

int function2() {
    //do stuff
    function1();
}

This is called a forward declaration. You let the compiler know that there is a function called function2()without defining it. This is enough for the compiler to introduce a call to this function when it is called internally function1(), which is then resolved during the link.

+1
source

Forward declaration function2 ().

int function2(); //forward declaration

int function1() {
    if (somethingtrue) {
        function2();
    }
}

int function2() {
    //do stuff
    function1();
}
+1
source

This will solve your problem:

int function2();

int function1() {
    if (true) {
        function2();
    }
}

int function2() {
    //do stuff
    function1();
}
+1
source

Source: https://habr.com/ru/post/1627471/


All Articles