Should I Explicitly Truncate?

Given this starting point:

double y = readDoubleValue(); 

Is there a significant difference in C ++ between:

 int x = y; 

and

 int x = trunc(y); 

Which one should I prefer? If someone else (including my future self :)) is reading my code, it seems to me that with the second it is a more obvious fact that I know exactly what I'm doing, but this requires the inclusion of a library.

Link: Is there a trunc function in C ++?

+8
c ++
source share
2 answers

Just using static_cast<int>(y) , you get all the benefits you are looking for:

  • truncation
  • casting
  • explicit conversion for clarity.

reasons why I will not use trunc()

  • This is not so often, and probably someone who reads your code will have to look through the documentation (which is why I did it, but again, I'm not an expert)
  • you use implicit conversion trunc() , trunc() does not return int.
  • for me, this is not clear enough, after reading your code and documentation, I asked myself this: "did he intend to pour on int, or do you just need a float without part of the share"

I can think of a situation or two where I want to get rid of part of the fractions, but I still want the variable to be of type float for several reasons like: I want the operation x + 0.1f save part of the fraction. therefore, I will nevertheless doubt your intentions, perhaps you did not mean the implicit conversion.

OR , you can simply add a small comment next to it int x = y; // yes, I know what I'm doing int x = y; // yes, I know what I'm doing .
It will also give you clarity.

+6
source share

IMO you shouldn't. Truncation is a function defined for floating point types. It does not change the type to an integral type.

int x = y; here you say you are assigning something to an int variable

int x = trunc(y); here you say that for some reason you drop part of the fractional part and then convert

The use cases are quite different in my opinion.

Why should I discourage the use of trunc before conversion. Probably a preference, for me a kind of confusion is actually in such a precedent.

0
source share

All Articles