Returning value in conditional operator

前端 未结 3 1682
陌清茗
陌清茗 2021-01-07 03:06

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()
{         


        
相关标签:
3条回答
  • 2021-01-07 03:26

    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.

    0 讨论(0)
  • 2021-01-07 03:26

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

    Try this instead:

    return (listSize > 0);
    
    0 讨论(0)
  • 2021-01-07 03:41

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

    0 讨论(0)
提交回复
热议问题