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

Viewed 536

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.

7 Answers
Related