[英]Returning value in conditional operator
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
谢谢
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. *) 由于您将其标记为 C 和 C++,因此请知道两种语言中可接受的表达式之间存在细微差别。
The ternary operator ( ?:
) is not designed to be used like that.三元运算符 (
?:
) 不是为这样使用而设计的。 You have a syntax error.您有语法错误。
Try this instead:试试这个:
return (listSize > 0);
Unless you have a deeper reason for doing this that I am missing, you should just return (listSize > 0);
除非你有更深层次的理由这样做我错过了,你应该只
return (listSize > 0);
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.