Should I initialize a floating-point (double,float) variable with 0 or 0.0?

My question is: Should i initialize a floating-point variable like a double or float with 0 or rather 0.0 (if i want to initialize it with a value equivalent to 0 of course)?

Like for example:

double var = 0.0;

in comparison to:

double var = 0;

Does it make a difference?


Question is open for C and C++, as i work with both and did not want to make the same question twice. If there is a significant difference between those two with regards to especially that case, please mention which language is in your focus.

With the half eye on C++, the case of the constructor might become also an influence to the topic and of course initialization in general is a broader topic in C++, but i don´t know whether this is influencing the answer or not.

Huge thanks.

Upvotes: 2

Views: 2486

Answers (2)

Anteino
Anteino

Reputation: 1136

A double you can just initialize like this:

double test = 0.0;

However, a float you have to initialize like this if you want to do it 100% correct:

float test = 0.0f;

The f means that the number that precedes it is a float. If you leave it out, the number is interpreted as a double and automatically casted back to a float because your variable is of type float. Leaving the f out doesn't cause any real trouble but it introduces unnecessary overhead. I believe something similar happens when you initialize a double with just 0 instead of 0.0, but I am not sure about this part.

Upvotes: 2

Paul Evans
Paul Evans

Reputation: 27567

As @NathanOliver comments, it doesn't make a difference in this case. But it's a good habit to always say what you mean:

double var = 0.0;

Where this habit will pay off is places like std::accumulate:

std::vector<double> v{1.2, 2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.9, 9.0, 10.1};

double sum = std::accumulate(v.begin(), v.end(), 0);  // 0 here is wrong!

this isn't going to work as std::accumulate is declared as:

template< class InputIt, class T >
constexpr T accumulate( InputIt first, InputIt last, T init );

so the 0 causes T to be int!

Upvotes: 4

Related Questions