I was trying to multiply two integers using recursion, and wrote this code, accidently:
//the original version
int multiply(int a, int b)
{
if ( !b )
return 0;
else
return a + multiply(a, b ? --b : ++b ); //accident
}
I said, I wrote this accidently, because I intended to write :
b > 0 ? --b : ++b
instead of b ? --b : ++b
I realize that what I intended to write wouldn't work. But what is surprising to me is, what I did not intend to write does work.
Now, I note that b ?--b : ++b
is basically equivalent to --b
because b
in else-block is guaranteed to be non-zero. So I modified the above code, replacing b?--b:++b
with --b
, as shown below:
//the modified version
int multiply(int a, int b)
{
if ( !b )
return 0;
else
return a + multiply(a, --b); //modification here
}
Since the original version woks, I expected the modified version to work as well. But again, to my surprise, it doesn't work!
--b
not equivalent to b ?--b : ++b
IF b
is non-zero? If its equivalent, then why does the first code work but the second doesn't? Note: here, by "work", I mean it gives the correct output. That is, it gives the multiplication of the integers passed to the function.
It doesn't work. I don't know what ideone is smoking, that code is going to overflow the stack.
EDIT
Tried it on gcc 4.6.0 - segfault (due to stack overflow). If however you enable -O2
optimizations, then indeed "it works". In conclusion: it works by chance, depending on what the compiler does behind the scenes.
g++ -g -Wall -o f f.cpp # stack overflow
g++ -O2 -g -Wall -o f f.cpp # "works"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With