Return x if not 0 else y

Is there a quicker way to write:

byte x = foo();
if (x)
    return x;
else
    return y;

It feels clunky, although looks small on the example.

return foo() ? foo() : y;

...could work, but if the return value of foo uses an input read then the value of the pin could change between the two foo() calls.

byte x = foo();
return x ? x : y;

Might be best?

The compiler will likely generate the same code for all the variations except for the one possibly where you call foo() twice if it can’t assess side effects

Get x
Test
Return what’s needed

Define what you mean by best

  • fastest to write ?
  • smallest code produced ?
  • fastest code produced ?
  • easiest to understand ?
  • something else ?

I would vote for easiest to understand. In any case it is likely that the compiler will optimise the code anyway so size and speed of operation become irrelevant to you

I suppose using/evaluating/writing x less often.

I did recently learn about branchless programming where I think if I understood an example correctly they'd combine the ternary as...

byte x = foo();
return x*(x>0) + y*(x<=0); // edit: thanks killzone_kid for the + fix

but that's harder to read, swaps one conditional for two, and (in writing) uses x even more!

Curious, what might the compiler do to optimise it?

Maybe i'm looking for something similar to the ternary that goes (obviously wrong) like:

'return if' foo() : y;

or

'return if(condition for first value)' foo() : y;

so

'return if(>0)' foo() : y;

Clearly the very first example is fine i'm just curious what other methods are out there.

this will always return 0

Yeah I think I buggered that up hey. First time even trying to think in that way. Maybe a plus between the two sides (edited it). I like the idea of it but it hurts my brain :smiley:

GCC allows you to omit the middle parameter of the ternary operator:

return foo() ? : 123;

I would do

byte x = foo();
if (x) return x;
return y;

and let the compiler / optimizer sort it out.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.