4

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

3 Answers3

16

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.

Community
  • 1
  • 1
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Thanks that you mentioned the difference. As it was just a snippet I thought it would be better to tag both languages. –  Aug 12 '11 at 21:25
  • The last one may look good. But when you enter debug time you will wish you had assigned the result to a temporary before returning so that it is east to inspect. – Martin York Aug 12 '11 at 22:35
  • @Kerrek By any chance, do we need to put the ternary condition inside braces? I got a code review comment to do that. – cppcoder Feb 19 '13 at 10:08
  • @cppcoder: You don't need to. But depending on how you use it, it might help the reader. Do *you* know what `a ? b : c = d` does? :-) – Kerrek SB Feb 19 '13 at 10:12
  • @Kerrek What will be the precedence here? I guess, it will assign `d` to `c` and return `c` if `a<=0` – cppcoder Feb 19 '13 at 10:28
  • @cppcoder: That's the point: If you have to guess, you should add parentheses :-) (And it's quite an interesting point what this expression really does.) – Kerrek SB Feb 19 '13 at 13:22
  • @KerrekSB Please reply what is the exact behavior. – cppcoder Feb 19 '13 at 17:59
6

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

Try this instead:

return (listSize > 0);
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
2

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

EmeryBerger
  • 3,897
  • 18
  • 29