When using float or double for int, is the behavior compatible across platforms?

For example, if I have:

float f = 3.3456;
float g = 3.676455;

int j = f;
int k = g;

      

When f, g values ​​are passed to int, will the behavior be the same across all platforms? Will j, k always be 3?

For example, will there ever be 4? Is the fractional part always truncated or is it always rounded?

The reason for this is slightly different from the question suggested as a duplicate, is that the conversion is implicit in this case. See the Noticeable answer, as it directly contradicts the marked answer in "recurring question".

+3


source to share


1 answer


[...] will the behavior be the same across all platforms?

Yes. Yes, it will.



From N4659 (my emphasis in bold ):

7.10 Floating Integral Conversions [conv.fpint]

(1) A floating point prvalue can be converted to an integer prvalue. The transformation truncates ; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the target type . P>

+4


source







All Articles