question about excerpt from "Accelerated C++"

J

Joe Laughlin

On 6.2.3/115 of "Accelerated C++", there's this function:

double average(const vector<double>& v)
{
return accumulate(v.begin(), v.end(), 0.0) / v.size();
}

The author notes that it's important to use 0.0 in the function, as
accumulate uses the third argument's type as its return type.

Wouldn't it be better to explicity say
return accumulate(v.begin(), v.end(), double(0)) / v.size();


Is there a chance that floats and doubles might get mixed up if you don't do
a cast?

Thanks,
Joe
 
B

BekTek

0.0 is double but double(0) is int casted to double..
furthermore, 0.0f is float..
But actually all are same..
compiler might generate same code, I suppose. :)
 
J

Joe Laughlin

BekTek said:
0.0 is double but double(0) is int casted to double..
furthermore, 0.0f is float..
But actually all are same..
compiler might generate same code, I suppose. :)

Doubles are different than floats, as far as I know.

I wasn't sure that 0.0 would automatically be a double.
 
A

Andrew Koenig

On 6.2.3/115 of "Accelerated C++", there's this function:

double average(const vector<double>& v)
{
return accumulate(v.begin(), v.end(), 0.0) / v.size();
}

The author notes that it's important to use 0.0 in the function, as
accumulate uses the third argument's type as its return type.

Wouldn't it be better to explicity say
return accumulate(v.begin(), v.end(), double(0)) / v.size();

The effect is exactly the same, because floating-point literals have type
double if you don't explicitly say otherwise. In other words, 0.0 has type
double, as does double(0), and 0.0f has type float. See page 303.
 
R

Ron Natalie

BekTek said:
0.0 is double but double(0) is int casted to double..
furthermore, 0.0f is float..
But actually all are same..
compiler might generate same code, I suppose. :)

The last one isn't the same, it's a float not a double.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top