-1

Here's a sample code where it is evident:

int foo();
void bar();

bool flag = false;

int foo()
{
    if(!flag) bar();
    cout<<"Reached Here!"<<endl;
    return 0;
}

void bar()
{
    flag = true;
    foo();
}

In this code, cout<<"Reached Here!"<<endl; is executed twice. However, simulating it step-by-step does not agree with that. From what I am expecting, it should go like this:

  1. Since !flag is true, call bar()
  2. From function bar(), set flag = true
  3. Then, call foo()
  4. Since !flag is now false, we just proceed to next line
  5. Output Reached Here to console
  6. End of Program

As you can see, I am expecting for cout<<"Reached Here!"<<endl; to only be executed once. So, why is it being executed twice and how can I avoid that (aside from enclosing the next lines with else)?

Edit: Changed foo() to bar() and changed main() to foo()

  • 1
    Recursive call of `main()` is illegal in C++. [Recursive call on main C++ - Stack Overflow](https://stackoverflow.com/questions/11349515/recursive-call-on-main-c) – MikeCAT May 07 '21 at 14:49
  • It's undefined behavior. Pretty futile to ask about how that will behave. – πάντα ῥεῖ May 07 '21 at 14:49
  • `main` is rather special, you can do `int main() { my_main(); }` and call `my_main` recursively – 463035818_is_not_an_ai May 07 '21 at 14:57
  • 2
    Regardless of the undefined behavior of calling main, I don't know why you expect it to only print once. `if (condition) { A; } B;` will execute `A` followed by `B` if the condition is true, and will execute only `B` if the condition is false. – Kevin May 07 '21 at 15:00
  • Don't worry, I'm only calling main for the sake of this example. Just think of it like some other function for now.... (nevermind I'll just edit that out lol) – Carl Eric Doromal May 07 '21 at 15:05
  • Please edit the question to have `main` call a separate function that does this logic and I'll vote to reopen. – Kevin May 07 '21 at 15:07
  • `bar` should call `foo` now instead of `main`? – Kevin May 07 '21 at 15:10
  • Yes. And it still have the same behavior as with any other function names. – Carl Eric Doromal May 07 '21 at 15:11

1 Answers1

3

When you return from functions, the execution continues from the line after the function call. This is what return means.

Therefore, the actual trace is:

  1. (1st call of) foo() calls bar(), seeing flag = false
  2. bar() sets flag = true
  3. bar() calls (2nd) foo()
  4. (2nd call of) foo() skips bar(), seeing flag = true
  5. (2nd call of) foo() prints "Reached Here!"
  6. (2nd call of) foo() returns zero to bar()
  7. bar() returns
  8. (1st call of) foo() prints "Reached Here!"
  9. (1st call of) foo() returns zero to its caller
MikeCAT
  • 73,922
  • 11
  • 45
  • 70