-2

1

double recursively(int n) {
    (n==0)?(return 0.0):((n==1)?(return 1.0):(return 2*recursively(n-1)+recursively(n-2)));
}

When I use the ternary operator in a recursive function it is not showing "expected an expressionC/C++(29)" error. I am using Visual Studio Code. Any possible reason?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • 1
    Please add the code as text, and not images. – cigien Jan 20 '21 at 09:16
  • 1
    Control flow keywords, such as `return` should not be used within expressions. It should be written in front of it. – user7860670 Jan 20 '21 at 09:17
  • "... it is not showing "expected an expressionC/C++(29)" error" when it is *not* showing an error, then whats the problem? is this a typo? – 463035818_is_not_an_ai Jan 20 '21 at 09:17
  • `return (n==0)?(0.0):(1.42);` – πάντα ῥεῖ Jan 20 '21 at 09:18
  • `return 0.0`, `return 1.0`, etc are statements, not expressions. As the error message says, the ternary operator expects expressions i.e. in `a ? b : c` it is necessary that `a`, `b,` and `c` all be valid expressions. That is also true when the expressions also use the ternary operator. The simple way is to move the `return` keyword outside, and remove all the other places where it is used i.e. `return (n == 0) ? (0.0) : ((n == 1) ? 1.0 :` – Peter Jan 20 '21 at 09:20
  • Try to avoid the ternary operator just to type lesss. The major usecase for the ternary operator is to initialize a variable directly. In your case you should use ```if```. – Henk Jan 20 '21 at 09:26

1 Answers1

1

The official name is "the conditional operator", and it is an expression that produces a value - a ? b : c is not shorthand for if (a) b; else c; but a choice between the values b and c.

Rewrite to return the value of the expression:

return n==0 ? 0.0 : (n==1 ? 1.0 : 2*recursively(n-1)+recursively(n-2));

The parentheses around n == 1 ? ... are technically redundant, but make it easier to read.
I sometimes break long lines like this:

return n == 0 
       ? 0.0 
       : n == 1 
         ? 1.0 
         : 2 * recursively(n-1) + recursively(n-2);
molbdnilo
  • 64,751
  • 3
  • 43
  • 82