简体   繁体   中英

Ternary Operator Clarification

Any suggestions on how to improve this? I want to assign the result of a calculation to a variable, but if it's 0, then I want to assign the value 1. The following works, but there must be a better way where I don't need to state the calculation twice:

int result = x-y > 0 ? x-y : 1;

Assuming you will always have a non negative integer result (ie no smaller than zero), then you can try using the following instead:

int result = Math.max(x - y, 1);

The logic here is that if the result should be zero, the above expression would assign 1 to the result. If the result be 1, then we also take 1, and for any result greater than 1, we keep that value.

I'm not sure we can simplify your ternary expression further. We could do this:

int result = x - y;
result = result > 0 ? result : 1;

But now we have two lines of code. In any case, the compiler might optimize what you wrote to what I wrote just above, ie the calculation might not be done twice anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM