整数除法的哪个操作数是 static_casted 是否重要以获得浮点数结果?
Does it matter which operand of integer division is static_casted to obtain a float result?
为了从两个 int
的除法中获得浮点数结果,我们 static_cast
一个操作数到 float
,像这样:
int a = 2;
int b = 3;
float c = static_cast<float>(a) / b; // c = 0.666666
float d = a / static_cast<float>(b); // d = 0.666666
在上面的例子中,static_cast
编辑了哪个操作数应该无关紧要。但是,假设其中一个操作数是编译时常量,而另一个不是,如下所示:
int a = foo(); // value not available at compile-time.
const int b = SOME_CONSTANT; // compile-time constant.
编译器优化是否对两个 static_cast
有任何影响,如下所述?
float c = static_cast<float>(a) / b;
在这种情况下,编译器可以用它的值替换 b
,但由于 a
未知,因此只能在运行时进行转换。
float d = a / static_cast<float>(b);
然而,在这种情况下,编译器知道 b
,因此它可以在编译时进行转换,并直接将 b
替换为 float
值。
在这两种情况下,在转换之后,integer/float(或float/integer)除法会在运行时发生。
这种直觉是否正确,或者编译器是否足够聪明,可以在两种情况下同样优化?还有其他我忽略的因素吗?
没有 int/float
或 float/int
划分在运行时发生。曾经。
由于一个操作数被转换为 - 显式转换 - 为 float
,另一个将被隐式转换为 float
以进行除法。
你的两种情况都等同于
static_cast<float>(a) / static_cast<float>(b);
为了从两个 int
的除法中获得浮点数结果,我们 static_cast
一个操作数到 float
,像这样:
int a = 2;
int b = 3;
float c = static_cast<float>(a) / b; // c = 0.666666
float d = a / static_cast<float>(b); // d = 0.666666
在上面的例子中,static_cast
编辑了哪个操作数应该无关紧要。但是,假设其中一个操作数是编译时常量,而另一个不是,如下所示:
int a = foo(); // value not available at compile-time.
const int b = SOME_CONSTANT; // compile-time constant.
编译器优化是否对两个 static_cast
有任何影响,如下所述?
float c = static_cast<float>(a) / b;
在这种情况下,编译器可以用它的值替换 b
,但由于 a
未知,因此只能在运行时进行转换。
float d = a / static_cast<float>(b);
然而,在这种情况下,编译器知道 b
,因此它可以在编译时进行转换,并直接将 b
替换为 float
值。
在这两种情况下,在转换之后,integer/float(或float/integer)除法会在运行时发生。
这种直觉是否正确,或者编译器是否足够聪明,可以在两种情况下同样优化?还有其他我忽略的因素吗?
没有 int/float
或 float/int
划分在运行时发生。曾经。
由于一个操作数被转换为 - 显式转换 - 为 float
,另一个将被隐式转换为 float
以进行除法。
你的两种情况都等同于
static_cast<float>(a) / static_cast<float>(b);