简体   繁体   English

C ++是否会自动将const int强制转换为浮点数?

[英]does C++ automatically cast const ints to floats?

I am aware that casting ints to floats (and vice versa) is fairly expensive. 我知道将int转换为float(反之亦然)是相当昂贵的。 However, does the compiler automatically do it at compile time for constants in your code? 但是,编译器是否会在编译时针对代码中的常量自动执行此操作? For eg is there any difference between 例如之间有什么区别

float y = 123;
float x = 1 / y;

and

float y = 123.f;
float x = 1.f / y;

I see some code that does the latter, but I'm not sure if it's for optimization or safety issues (ie just making sure that the divide is floating point even if y happens to be an int). 我看到一些执行后者的代码,但是我不确定是否用于优化或安全性问题(即,即使y恰好是一个整数,也要确保除法是浮点数)。

I'm using gcc (since the answer might be compiler specific.) 我正在使用gcc(因为答案可能是特定于编译器的。)

Also, any pointers to a list of what the compiler can and cannot optimize in general would be appreciated. 同样,通常会想到指向编译器可以优化和不能优化的列表的任何指针。 Thanks! 谢谢!

Yes, the compiler will do the conversion automatically. 是的,编译器将自动进行转换。 Your two blocks of code are identical. 您的两个代码块是相同的。

It is not an optimization. 这不是优化。 Turning off optimization won't make the compiler include the int-to-float conversion in the executable code, unless it's a very poor-quality implementation. 关闭优化不会让编译器包含可执行代码的INT-漂浮的转换,除非它是一个质量非常差的执行。

It's not for safety, either. 也不是为了安全。 The compiler never does anything "just in case" an operand happens to be of a different type. 编译器绝不会做任何“以防万一”操作数恰好是不同类型的事情。 The compiler knows the types of everything in your code. 编译器知道代码中所有内容的类型。 If you change the type of a variable, everything that uses that variable gets recompiled anyway; 如果更改变量的类型,则使用该变量的所有内容都会被重新编译; the compiler doesn't try to keep everything else untouched and just update the changed sections. 编译器不会尝试保持其他所有内容不变,而只是更新更改的部分。

Yes, it definitely does so, so the two snippets are equivalent. 是的,它确实是这样做的,所以这两个片段是等效的。 The only thing that matters is the type of the variable you assign to. 唯一重要的是分配给变量的类型。

The float y=123 and float y = 123.f cases should be the same for most compilers, but float x=1/y and float x=1.f/y will actually generate different results if y is an integer. 对于大多数编译器, float y = 123float y = 123.f的情况应该相同,但是如果y是整数, float x = 1 / yfloat x = 1.f / y实际会产生不同的结果。

It really does depend on the compiler - some might actually store a constant int and convert it each time it gets assigned to a float variable. 它确实确实取决于编译器-有些可能实际上存储了一个常量int,并在每次将其分配给float变量时对其进行转换。

There are cases where the compiler casts float to int, eg 在某些情况下,编译器将float强制转换为int,例如

float f;
if (f > 1) ...

In this case I have had it happen (Visual Studio 2008) that the compiler produced code equivalent to 在这种情况下,我发生过这种情况(Visual Studio 2008),编译器生成的代码等效于

if (int (f) > 1) ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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