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.
The syntax is invalid. Ternary conditional operator requires its operands to be expressions, but
return 1
andreturn 0
are not.On the other hand, return statement could be used with an (optional) expression, such as a ternary conditional operator:
So you could/should write it as