0

I am writing a simple factorial function to practice recursion within c++. I wanted to write it in ternary format but it was not working so I wrote it out first to see if it worked the more traditional way.

Ternary Format:

   num > 1 ? num * factorial(num-1) : return 1;

Traditional :


   if (num > 1){
    return num * factorial(num-1);
   }
   else {
    return 1; 
   }

I am simply printing the result of factorial(5) which should display 120. While it works for the second it does not for the first. Why can I not use return in the ternary format? Or, am I using it wrong?

Colin
  • 13
  • 4

1 Answers1

2

You can use factorial just fine in the conditional form, but you can't use return. return is a statement, whereas the conditional operator expects expressions. Conveniently, the conditional operator itself is an expression, which lets you do this.

return num > 1 ? num * factorial(num-1) : 1;

Note that we're returning the result of the whole expression, not just the num > 1 piece. If I wanted to be redundant with parentheses, I could do this, which is semantically equivalent.

return (num > 1 ? num * factorial(num-1) : 1);
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116