Reputation: 1715
Going through some code, I found this :
#ifdef trunc
# undef trunc
#endif
inline float trunc(float x)
{
return (x < 0.0f) ? float(int(x)) : float(int(x));
}
inline double trunc(double x)
{
return (x < 0.0f) ? double(int(x)) : double(int(x));
}
inline long double trunc(long double x)
{
return (x < 0.0f) ? (long double)(int(x)) : (long double)(int(x));
}
#endif // _WIN32
Of course, the ?: operator always returns one and the same value in each case, regardless of its conditional expression. On the other hand, I guess the author had his reasons to write these functions this way; I can't find one though. Any idea ? Is this just an error (typo) ?
[EDIT] Reply from the author :
Good point - this is just overzealous cut-and-paste from the definition of round(). The following should be just fine (other than the limitation on the range of int):
inline float trunc(float x)
{
return float(int(x));
}
inline double trunc(double x)
{
return double(int(x));
}
inline long double trunc(long double x)
{
return (long double)(int(x));
}
Upvotes: 2
Views: 221
Reputation: 17956
This code looks wrong.
My guess is that they meant something more like this:
inline float trunc(float x)
{
return (x < 0.0f) ? -float(int(-x)) : float(int(x));
}
But even that's dubious. I believe int(x) always performs truncation, so even then the two branches of ?:
should yield the same result.
In case rounding mode does matter to the typecast (and after a moment's thought, I'm not sure it does), you may really want to use a function like modf
, modff
or modfl
to break the number into integer and fractional portions, and discard the fractional portion.
For example:
inline float trunc(float x)
{
float int_part;
modf(x, &int_part);
return int_part;
}
Edit: One other observation. The original code will fail for values that do not fit in an int
. Yet another strike against it.
Upvotes: 5
Reputation: 11080
The code returns the same output for both the conditions. This is just a redundancy and moreover, the float(int(x))
doesn't make a point. Because int(x)
converts the number to an integer, again converting it to float or double makes no difference but only the type of the variable returned.
Upvotes: 0