0

Why this c++ code produce a Runtime Error?

anyone could help me?

https://ideone.com/trZwFD

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.

5
  • 4
    It is written in three languages? Commented Jan 18, 2015 at 11:36
  • yes, it's in java, and i re-write it for C++. Commented Jan 18, 2015 at 11:37
  • 1
    So it isn't written in three languages then. Commented Jan 18, 2015 at 11:37
  • it's not fair, to negative point to my question. Commented Jan 18, 2015 at 11:38
  • 2
    test(a,b); : Because the state is call unchanged and stack overflow by repeated calls. Commented Jan 18, 2015 at 11:40

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

if we replace it with static int temp =1, is it true?
@user4249446 Is what true?
i means the recursion becomes true and end ?
temp %b will be non-zero for all values of a and b, and will give an exception for 0. So the if will never be true so you will always recurse => stack overflow if a and b non-zero, divide bv zero if a or b are zero.
0
#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

1 Comment

How this can work ? the last line of the function should be return test(a,b); . The result is ok.
0

I think you should give up recursion - what you want to do just don't justifies it.

int test(int a, int b)
{
     int temp = 1;
     while (temp % b == 0 && temp % a == 0)
        ++temp;
     return temp;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.