Recurssion: Why one crashes ?

C

codefixer

Hello:

I am trying to understand why one of these crash while the other works
fine.
long recurssion(int t)
{
if(t <= 1)
return(1);
else
return(t * recurssion(t--)); //crashes
}

long recurssion(int t)
{
if(t <= 1)
return(1);
else
return(t * recurssion(t-1)); //works fine
}

Thanks.
 
M

Mike Wahler

Hello:

I am trying to understand why one of these crash while the other works
fine.
long recurssion(int t)
{
if(t <= 1)
return(1);
else
return(t * recurssion(t--)); //crashes

return(t * recurssion(--t));
}

long recurssion(int t)
{
if(t <= 1)
return(1);
else
return(t * recurssion(t-1)); //works fine
}

The expressions 't--' and 't-1' do not have the same
value. Read about 'post-increment operator' and
'pre-increment operator'.

-Mike
 
P

Peter Nilsson

Mike said:
return(t * recurssion(--t));

Both invoke undefined behaviour as they reference t for a purpose
other than to calculate it's new value prior to the next (guaranteed)
sequence point.
 
K

Keith Thompson

I am trying to understand why one of these crash while the other works
fine.
long recurssion(int t)
{
if(t <= 1)
return(1);
else
return(t * recurssion(t--)); //crashes
}

long recurssion(int t)
{
if(t <= 1)
return(1);
else
return(t * recurssion(t-1)); //works fine
}

Add this as the first statement of each function and try running it:

printf("Entering recurssion, t = %dl\n", t);

(BTW, the correct spelling is "recursion".)
 
K

Kenneth Brody

Hello:

I am trying to understand why one of these crash while the other works
fine. [...]
return(t * recurssion(t--)); //crashes [...]
return(t * recurssion(t-1)); //works fine
[...]

What is the value of "t--" as compared to "t-1"?

For example, given "x = recurssion(37);", what will be the value passed
to the first recursion? What will the first pass to the second? And so
on.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:[email protected]>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top