Reputation: 151
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.
Upvotes: 2
Views: 2144
Reputation: 172884
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;
Upvotes: 7
Reputation: 112
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;
Upvotes: 1