Given this starting point:
double y = readDoubleValue();
Is there any significant difference in C++ between:
int x = y;
and
int x = trunc(y);
Which one should I prefer? If somebody else (including my future self :) ) reads my code, it looks to me that with the second it's more explicit the fact that I know exactly what I am doing, however it requires a library inclusion.
Reference: Is there a trunc function in C++?
Just using static_cast<int>(y)
will give all the benefits you are looking for:
the reasons why I won't use trunc()
trunc()
doesn't return an int.I can think of a situation or two where I want to get rid of the fraction part but I still want to the variable to have the type float
for several reasons like, I want the operation x + 0.1f
to save the fraction part.
so I still would have doubts about your intentions, maybe you didn't mean the implicit conversion.
OR you can just put a little comment next to it int x = y; // yes, I know what I'm doing
.
This will also give the clarity you need.
IMO you should not. The truncate is a function defined for floating point types. It does not change type into integral type.
int x = y;
here you say you are assigning something to an int variable
int x = trunc(y);
here you say you drop the fractional part part for whatever reason, then convert
Use-cases are pretty different in my opinion.
Why would I discourage use of trunc
before conversion. Probably preference, to me its kind of obfuscation actually in such use-case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With