-1

I can define variables using the (? :) operators. But why I can't use it as an if-else statement to execute statements based on a condition?

I tried doing the following:

char first = queue.remove();
(first == 'W') ? women++ : men++;

But did not work.

2 Answers2

4

That's called the ternary operator, and it results in an expression, not a statement. Semi-colons follow statements.

The following is valid because it's both a statement and an expression (if the return type of foo is void, then it's only a statement):

foo();

And the following is invalid for the same reason your ternary operator example is invalid (a literal string is only an expression):

"xyzzy";

If you want to execute one statement or another depending on a boolean, use an if-then statement. If you want an expression to take one value or another depending on a boolean, use the ternary operator. They're not interchangeable.

gdejohn
  • 7,451
  • 1
  • 33
  • 49
0

While if-statement's allow the logical flow of code, the ternary operator is actually an operation that takes three operands. The ternary operator results in an expression, not a statement.