Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I explicitly trunc?

Tags:

c++

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++?

like image 577
Antonio Avatar asked Jan 08 '14 09:01

Antonio


2 Answers

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

  1. truncation
  2. the casting
  3. explicit conversion for clarity.

the reasons why I won't use trunc()

  1. it is not that common, and probably someone else reading your code will have to review the documentation (that is why I did, but again, I'm not an expert)
  2. you are still using implicit conversion anyway, trunc() doesn't return an int.
  3. for me it is not explicit enough, after reading your code and the documentation I asked myself this: "did he intent casting to int, or you just wanted a float without the fraction part"

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.

like image 170
Moha the almighty camel Avatar answered Sep 28 '22 21:09

Moha the almighty camel


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.

like image 26
luk32 Avatar answered Sep 28 '22 19:09

luk32