Ternary Operator. true is empty

I was wondering how this code would look like with the ternary operator

if (a) {
    // pass
} else {
    b(); 
}

We got no(thing) code to execute when a is true but in case a is false there is some code b() which is then executed.

So we write that:

a ? : b();

But I am not sure if that is correct when you let the code for true empty or if you have to replace it with something. Actually I never use the ternary operator but we were asked to do so.

Jon Skeet
people
quotationmark

That's not what the conditional operator is for... it's not to execute one statement or another, it's to evaluate one expression or another, and make that the result of the expression.

You should write your code as:

if (!a) {
    b();
}

Actually I never use the ternary operator but we were asked to do so.

If you were asked to do so for this particular situation, then I would be very wary of whoever was asking you to do so. My guess is that it was actually not quite this situation...

people

See more on this question at Stackoverflow