George Newton
George Newton

Reputation: 3303

Converting float to int, with and without cast

Are these two equivalent?

float f = 3.14;
int i;
i = f; // 3

And

float f = 3.14;
int i;
i = (int) f; // 3

Upvotes: 8

Views: 5544

Answers (5)

hamlatzis
hamlatzis

Reputation: 81

the second conversion is also known as c-cast and should be avoided, at least in c++, better use static_cast

When using static_cast the compiler will check if the conversion can happen (ie one type can be converted to the other), when using the old style it will always do the conversion even if they aren't compatible

Upvotes: 0

Violet Giraffe
Violet Giraffe

Reputation: 33607

There is no difference in the ways compiler treats these 2 cases. The resulting machine code will be the same. However, the first is implicit conversion, and the second is explicit conversion. Depending on compiler flags, you may get a warning when performing implicit conversion that loses precision.

On a side note, the literal 3.14 has type double, which means that there's also possible precision loss in the statement float f = 3.14. A clean way would be to write float f = 3.14f which specifies that this is the value 3.14 of type float.

Upvotes: 9

Tu Bui
Tu Bui

Reputation: 1692

the compiler is intelligent enough to treat both cases the same. But I prefer the 2nd method as it is easier to read in a large program. Also it is recommended to specify the type you are casting in explicit conversion. Finally, your 1st method may not work in C#.
Ref: http://msdn.microsoft.com/en-us/library/ms173105.aspx

Upvotes: 0

Lee Duhem
Lee Duhem

Reputation: 15121

They are the same.

Tested with GCC 4.8.2 on 32-bit x86 system.

gcc -Wall -Wextra -Wpedantic will NOT give any warnings while compiling this code, but with -Wconversion it will.

Upvotes: 7

Wojtek Surowka
Wojtek Surowka

Reputation: 21003

Yes those are equivalent, no difference whatsoever.

Upvotes: 4

Related Questions