在C++中,我想测试传递给函数的值是否为非零,并在该条件下基于某些行为.
例如:
void do_something(float x){
if(x) // <-- prefer this format?
do_a();
else
do_b();
}
Run Code Online (Sandbox Code Playgroud)
VS:
void do_something(float x){
if(x != 0) // <-- or this format?
do_a();
else
do_b();
}
Run Code Online (Sandbox Code Playgroud)
其他形式:
void do_something(int x){
x? do_a() : do_b(); // <-- prefer this?
x!=0? do_a() : do_b(); // <-- or this?
}
Run Code Online (Sandbox Code Playgroud)
这些都是"形成良好",或者是否有某种原因在某些情况下会出现未定义的行为?
我在godbolt.org上测试过,两种形式都生成完全相同的汇编代码.我使用int,float,ternary运算符和if()进行了测试,并且在所有情况下,代码对于两种形式看起来都相同.
我目前倾向于使用if(x != 0)为float/ double,和if(x)为int,有些是由于不同的NaN的浮点值的复杂性,以及其它特殊值.