Home > Software engineering >  how to control recursion in cpp
how to control recursion in cpp

Time:08-12

Hi I am building a project using cpp in that I am heavily using recursion but I am not able to get

void user1() {
       avg=average(totall, dice);
        if(avg>=3){
            totallSum =totall;
            // cout<<name1<<" is safe! "<<name1<<"'s turn is score now "<<totallSum<<endl;
            if(totallSum<point){
                cout<<name1<<" is safe! "<<name1<<"'s turn is score now "<<totallSum<<endl;
            }
            else { 
                user1totall =totallSum;
                break;
            }
        }
        else{

            totallSum=0;
            user2(name1, name2,point,5,0,user1totall,user2totall,  turn2);
        }
        user2(name1, name2,point,dice,totallSum,user1totall,user2totall,  turn2);
}

this is the small snippet of the code I wrote here the issue is that in the else block where the user2 function is being called it works completely fine but when it is executed completely it don't exit this user1 function instead it agains call the user2 function on the second last line can anyone please tell how to resolve this issue

CodePudding user response:

It's because the memory is stored in stack (Last in First out). When its calling user2 function first time then the program will complete its execution first due to Stack memory after it has executed user2 function then it will continue again back to user1 and move next where it is again calling user2.

To resolve this error change user1 return type from void to int and when you are calling user2 function after that line add return 0; it will work completely fine

  • Related