Reputation:
Program -
Function that accepts current year and the birth year, computes the age
The problem -
Program crashes
The code-
int Age(int curr, int birth)
{
if (curr > birth)
{
return 1 + Age(curr--, birth);
}
return 0;
}
the input in function main is:
printf ("%d\n", Age(2014,1989));
Thanks for the help
Upvotes: 1
Views: 88
Reputation: 3057
In curr--
you are doing post decremented, decrements will affect in next line. so the value passed to function is always same as curr
,
You should do '--curr' so it will decrements curr value before calling of function.
Upvotes: 1
Reputation: 70941
It should be
... Age(--curr, birth);
as curr
shall be decremented before Age()
is being called.
Using The decrement applied to curr--
decrements curr
curr
by curr--
takes effect after Age()
returned, which will never happen, as the programm runs into a stack overflow due to trying infinit recursion.
Upvotes: 6
Reputation: 309
I guess this could be simply done as
age = curr-birth-1
without worrying about recursion.
Upvotes: 1