I can put a return anywhere such as in a function, in an if block, case block.
How come this doesn’t work:
(x == "good") ? (return("works")):"";
UPDATE: I know I can do this:
return (x == "good") ? ("works"):"";
Just want to know why the first case isn’t acceptable.
It’s because the grammar of a ternary operation is this:
And a return statement isn’t technically considered an expression.
Edit: here’s some more info. The above explains it in terms of the grammar of the language, but here’s a little bit about the reasoning of why.
I’ve actually dug into this before, because I’ve always thought it would be cool to be able to do stuff like:
Rather than
The problem, however, is that expressions always need to evaluate to something. This requirement is at odds with the role of the return statement, however, which along with (optionally) returning a result, also immediately terminates execution of the current function. This termination of the current function is logically inconsistent with the need to evaluate the value of the return statement itself, if it were indeed an expression.
Given that inconsistency, the language authors apparently chose to not allow return statements to act as expressions. Hope I managed to word that in a way that makes sense.