Zhang Yifan
Zhang Yifan

Reputation: 233

is there any difference between f+=1 and f+=1.0 if f is a double?

Suppose we have double f;

Is any difference between f+=1 and f+=1.0 ?

How does the compiler handler these situations?

I tried on my computer and loop 1010 times, the elapsed time is almost the same

Upvotes: 3

Views: 274

Answers (4)

Nikos Athanasiou
Nikos Athanasiou

Reputation: 31549

You can always check it for your system :

#include <iostream>
#include <type_traits>

using namespace std;

int main() 
{
    double f(0.);
    cout << std::is_same<decltype(f+1), decltype(f+1.)>::value << endl;
    return 0;
}

If anyone finds a case where they differ I'd appreciate a comment

Upvotes: 0

Matteo Italia
Matteo Italia

Reputation: 126867

No difference in any self respecting compiler, the implicit cast will surely be performed at compile time, probably even with optimizations disabled. If you have some doubt however you can always check the generated assembly.

Now, stylistically speaking, I prefer to always have my constants of the "correct" type (especially in expressions where some terms may get changed to int later), although some people think that all the trailing .0 just add visual clutter (but: you can avoid the trailing 0 and just leave the dot to specify a double literal - as in 1.).

Upvotes: 2

user1196549
user1196549

Reputation:

There can be a slight difference in a non-optimized build: the integer constant 1 can (should ?) be promoted to double at run-time rather than compile-time.

Upvotes: 0

damg
damg

Reputation: 689

Referring to c++03 here.

4.9 Floating-integral conversions [conv.fpint]

An rvalue of an integer type or of an enumeration type can be converted to an rvalue of a floating point type. The result is exact if possible. Otherwise, it is an implementation-defined choice of either the next lower or higher representable value.

If your system can represent 1.0 exactly (and looks like it can), then the expressions are same.

Upvotes: 3

Related Questions