"Do nothing" using ternary operator [duplicate]
Asked Answered
B

2

40

I want to use the ternary operator like this - checking only the true part of the statement:

foo() ? bar() : /* Do nothing */;

Is it possible to exclude the logic of the "else" part of this statement? I tried using return; but the compiler gives the error. Basically all I want to achieve is a statement using ternary operator which would look like this:

foo() ? bar();

Is this achievable?

Bloodstock answered 15/6, 2015 at 22:52 Comment(4)
Why would you not just use if? (No, it's not possible)Anyplace
I am just curious if that's even possible. That is all.Bloodstock
That doesn't actually make any sense. Expressions must have a value.Ezzo
I believe this is actually a desire to have a shorthand for simple if statements, keeping code compact (single line even with IDE formatters, no brackets). Closest semi-valid option is partial short-circuiting with foo() && bar(), since bar() only executes when foo() is true.Midvictorian
A
43

The ternary operator is usually used to immediately assign a value.

String a = bar() ? foo() : null;

For your usecase, you can simply use an if construct:

if (foo())
    bar();
Appraisal answered 15/6, 2015 at 22:56 Comment(3)
Not wrapping the if clause body in braces goes against the good code formatting practices, so this usually becomes if (foo()) { bar(); } (three lines)Upstanding
@IvanMatavulj: that's a matter of taste, and most definitely not a generally accepted best practice. I personally feel brackets are redundant in this case and don't add to readability. I agree with this passionate answer on this topic: programmers.stackexchange.com/a/16550Appraisal
I got an error using null I'd rather use void(0)Brocade
M
6

If it would work like that we wouldn't call it ternary anymore. I think the only way is that do something which does nothing. for example call a method which has empty body, or if you assign a value from this operation to a variable just assign a default value.

Maidel answered 15/6, 2015 at 23:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.