In C++, I want to test values passed to a function for being non-zero, and base some behavior on that condition.
e.g.:
void do_something(float x){
if(x) // <-- prefer this format?
do_a();
else
do_b();
}
vs:
void do_something(float x){
if(x != 0) // <-- or this format?
do_a();
else
do_b();
}
other forms:
void do_something(int x){
x? do_a() : do_b(); // <-- prefer this?
x!=0? do_a() : do_b(); // <-- or this?
}
Are both of these 'well formed', or is there a reason that either would be undefined behavior in some case?
I tested on godbolt.org, and both forms produce the exact same assembly code. I tested with int, float, ternary operator and if(), and in all cases the code looked the same for the two forms.
I currently tend to use the if(x != 0)
for float
/double
, and if(x)
for int
, somewhat due to the complexities of NaN, and other special values in the floating point value.