(float) in c / c++
Trying to find out what the (float) in this function means:
static float avgEndpoints (int i, int stride, float *fa)
{
return ((float) (fa[i-stride] +
fa[i+stride]) * .5f);
}开发者_StackOverflow社区
The reason I'm confused is the function already returns floating point (or appears to), so what is the (float) doing there?
I'm attempting to port this program to another language and learn a bit of c/c++ at the same time.
Thanks
The (float)
is a cast, which in this example casts the expression (fa[i-stride] + fa[i+stride])
to floating point.
In this case the cast is redundant and not required (as the expression will be a float anyway due to the *.5f
)
I think it is useless in this context. The intent was to have/cast return value as float, but
(fa[i-stride] + fa[i+stride]) * .5f
is already a float so, don't see any reason for another (float)
which is redundant.
Looks to me like it's redundant; you don't really need it there, but you might have if for some reason the compiler was trying to make that a double or something, which it would have done if it read ".5" instead of ".5f".
You can safely remove it without changing anything.
That "(float)" is called a cast. It forces the compiler to treat the result that follows as a float regardless of what it would otherwise be. For more information see this wiki page.
It is a redundant cast, just as the outer parenthesis is redundant. I would too ask the programmer who has written that code why they are doing what they do. It appears that they were not sure how the C language works.
Completely equivalent but clearer code:
return (fa[i-stride] + fa[i+stride]) * .5f;
This code
(float)
is a cast, which will force the expression fa[i-stride] + fa[i+stride]
to be converted to a float
.
For this code, this is a case of throwing in an unnecessary extra cast - just like throwing in an extra pair of parentheses (which this code also does).
I'd recommend removing extra unneeded parentheses, and learning the C++ standard order of operations/type promotions.
Cases where you'd need a cast
If that fa[i-stride] + fa[i+stride]
expression returned a double
instead, then there may be a subtle floating-point difference if you remove the cast.
Also if fa[i-stride] + fa[i+stride]
returned an integral type, then it is sometimes possible you'd need to cast to float to ensure that the answer wouldn't be integral-truncated.
However, the C++ standard's order of operations/type promotion determines whether this will happen or not. If those rules make the cast unnecessary, then you can (and probably should) take them out.
精彩评论