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?

5
  • 2
    The ternary operator resolves to a value. It's not a block. Commented Oct 30, 2013 at 15:52
  • 2
    Nitpick: Shouldn't x = (x > 0) ? x-- : x++; be x = (x > 0) ? --x : ++x;? Or even better: x = (x > 0) ? x - 1 : x + 1; Commented Oct 30, 2013 at 15:52
  • No. Let the compiler deal with those semantic issues. Commented Oct 30, 2013 at 15:54
  • 1
    Aaack. Please don't write code that assigns to a variable and uses a post-increment or pre-increment on the same variable. It gives me a headache. Commented Oct 30, 2013 at 16:14
  • 1
    Sorry about the unary increments. Edited it. Commented Oct 30, 2013 at 16:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I see countless x=x assignments taking place in some place. seems kinda silly and inefficient if that can happen.
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;
@ChthonicProject: Interesting, apparently that's a GNU-specific extension. I did check the JLS earlier; didn't see anything saying either of the second and third operands is optional (in Java).
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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.