Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Call function that is not defined yet

Tags:

c++

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

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

int function2() {
    //do stuff
    function1();
}
like image 457
Noah Avatar asked Dec 02 '22 15:12

Noah


1 Answers

This is a case for a forward declaration. A forward declaration tells the compiler that the name is going to exist, what it's type is and allows you to use it in a limited context before you define it.

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();
}
like image 127
NathanOliver Avatar answered Dec 21 '22 12:12

NathanOliver