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:
- Since
!flag
is true, callbar()
- From function
bar()
, setflag = true
- Then, call
foo()
- Since
!flag
is now false, we just proceed to next line - Output
Reached Here
to console - 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()