Why this c++ code produce a Runtime Error?
anyone could help me?
int test(int a, int b)
{
int temp=1;
if (temp % b ==0 and temp % a ==0)
return temp;
temp++;
test(a,b);
return temp;
}
Thanks to all.
Why this c++ code produce a Runtime Error?
anyone could help me?
int test(int a, int b)
{
int temp=1;
if (temp % b ==0 and temp % a ==0)
return temp;
temp++;
test(a,b);
return temp;
}
Thanks to all.
Each recursive call initializes temp to 1, so you never return from the method (assuming (1 % b ==0 and 1 % a ==0) is false for the given a and b), and always make another recursive call.
#include<iostream>
#include<iomanip>
using namespace std;
int temp=1;
int test(int a, int b)
{
if (temp % b ==0 && temp % a ==0)
return temp;
temp++;
test(a,b);
}
int main(){
cout<<test(2,3);
}
This code works well
return test(a,b); . The result is ok.
test(a,b);: Because the state is call unchanged and stack overflow by repeated calls.