7

This question is more for my curiosity than anything else.

I often employ Java's ternary operator to write shorter code. I have been wondering, however, whether it is possible to use it if one of the if or else conditions are empty. In more details:

int x = some_function();
if (x > 0)
    x--;
else
    x++;

can be written as x = (x > 0) ? x-1 : x+1;

But is it possible to write if (x > 0) x-1; as a ternary expression with an empty else clause?

Chthonic Project
  • 8,216
  • 1
  • 43
  • 92

1 Answers1

15

But is it possible to write if (x > 0) x--; as a ternary expression with an empty else clause?

No, the conditional operator requires three operands. If you wanted, you could do this:

x = (x > 0) ? x - 1 : x;

...but (subjectively) I think clarity suffers.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 2
    I see countless x=x assignments taking place in some place. seems kinda silly and inefficient if that can happen. – Plasmarob Oct 30 '13 at 15:55
  • I agree, clarity certainly suffers. I was curious about Java's take on it since in C (using GCC compiler), one may write something like `x = (x>0) ?: x+1;` – Chthonic Project Oct 30 '13 at 16:26
  • 1
    @ChthonicProject: Interesting, [apparently](http://stackoverflow.com/a/2806311/157247) that's a GNU-specific extension. I did [check the JLS](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25) earlier; didn't see anything saying either of the second and third operands is optional (in Java). – T.J. Crowder Oct 30 '13 at 16:30
  • Thanks for the link. I didn't know it was GNU-specific, and would have tried it on other platforms too ... and suffered! This was a big help (hence the upvote). – Chthonic Project Oct 30 '13 at 16:40