Why is the ternary operator not working in my code?

1.9k Views Asked by At

I have the following piece of code

mystack.empty() ? return 1 : return 0;

which looks perfect from the syntax point of view but whenever I try to run it throws an error saying

[Error] expected ':' before 'return'

and

[Error] expected primary-expression before 'return'

Do ternary operator don't work with return statements or is there something wrong with the code? And I guess the code is self explanatory.

Thank you.

2

There are 2 best solutions below

5
On

The syntax is invalid. Ternary conditional operator requires its operands to be expressions, but return 1 and return 0 are not.

On the other hand, return statement could be used with an (optional) expression, such as a ternary conditional operator:

attr(optional) return expression(optional) ; (1)

So you could/should write it as

return mystack.empty() ? 1 : 0;
0
On

return is an statement and rule is that you cant invoke a statement into a expression.

try reformatting code and using following (Assuming that function return a boolean value)

return  mystack.empty()? 1:0;