不明白 "if" 条件下发生了什么?
Don't understand what's going on in the "if" condition?
有点奇怪的问题。但遗憾的是。看不懂Unreal C++代码里condition里写的逻辑。
我在一个成员函数中有条件:
void MoveForward(float amount)
{
if (amount)
{
// do that
}
}
条件中的“金额”参数是什么意思?验证是为了什么?如果是安装?还是 true?
很抱歉这个扭曲的问题,不幸的是目前这一切都是新的...
在 C 和 C++ 中 if
测试非零值。任何非零的都被认为是真的。当谈到浮点值时,零到底是什么是书本上可以而且已经写过的东西,所以如果你想要可靠的代码就不要这样做。可以安全地假设它测试 amount != 0.0f
.
但就编译器而言,浮点数可以隐式转换为整数,并且可以测试非零值。
如果amount
不为零,则视为true
;如果amount
为零,则视为false
。
引用自N3337 6.4 选择语句
4 The value of a condition that is an initialized declaration in a statement other than a switch statement is the
value of the declared variable contextually converted to bool (Clause 4).
引用自 N3337 4.12 布尔转换
1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a
prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false;
any other value is converted to true.
有点奇怪的问题。但遗憾的是。看不懂Unreal C++代码里condition里写的逻辑。
我在一个成员函数中有条件:
void MoveForward(float amount)
{
if (amount)
{
// do that
}
}
条件中的“金额”参数是什么意思?验证是为了什么?如果是安装?还是 true? 很抱歉这个扭曲的问题,不幸的是目前这一切都是新的...
在 C 和 C++ 中 if
测试非零值。任何非零的都被认为是真的。当谈到浮点值时,零到底是什么是书本上可以而且已经写过的东西,所以如果你想要可靠的代码就不要这样做。可以安全地假设它测试 amount != 0.0f
.
但就编译器而言,浮点数可以隐式转换为整数,并且可以测试非零值。
如果amount
不为零,则视为true
;如果amount
为零,则视为false
。
引用自N3337 6.4 选择语句
4 The value of a condition that is an initialized declaration in a statement other than a switch statement is the value of the declared variable contextually converted to bool (Clause 4).
引用自 N3337 4.12 布尔转换
1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.