Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given that b is always non-zero, why `b ? --b : ++b` works, but `--b` does not?

Tags:

c++

recursion

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!

  • What is wrong the modified version?
  • Is it not equivalent to the original version?
  • Is --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.

like image 283
Nawaz Avatar asked Jun 17 '11 13:06

Nawaz


1 Answers

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"
like image 182
cnicutar Avatar answered Sep 17 '22 22:09

cnicutar