Returning value in conditional operator

妖精的绣舞 提交于 2019-12-19 10:11:13

问题


I was trying to return value true or false depending upon the condition by using a conditional operator but I got an error. Here is my code,

bool isEmpty()
{
    int listSize = Node::size();
    listSize > 0 ? return (true) : return (false);
    return false;
}

And here is the error,

error C2107: illegal index, indirection not allowed

Now I am stuck here. I don't get the point.Logically I think it should be correct. Please guide me about it . Thanks


回答1:


You can only have expressions* as the operands of the ternary conditional, not statements. The usual way to say this is:

return listSize > 0 ? true : false;

or even better,

return listSize > 0;

or even better,

bool isEmpty() { return Node::size() > 0; }


*) Since you tagged this as both C and C++, know that there is a subtle difference between the admissible expressions in the two languages.




回答2:


The ternary operator (?:) is not designed to be used like that. You have a syntax error.

Try this instead:

return (listSize > 0);



回答3:


Unless you have a deeper reason for doing this that I am missing, you should just return (listSize > 0);.



来源:https://stackoverflow.com/questions/7046120/returning-value-in-conditional-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!