0

I think this question is not new, but I can not find an answer anywhere.

Is there a difference between (double)myInt and double(myInt) in c++?

NelDav
  • 785
  • 2
  • 11
  • 30
  • No difference in effect. The former is a C-style cast, and is in general disfavor. The latter is a constructor-style cast, and is in general disfavor as well. The generally advocated way is to use a static cast, `static_cast(myInt)` – Eljay Feb 13 '20 at 13:15
  • Though it's okay in this case, but please bless others by using `static_cast` instead. Always. – theWiseBro Feb 13 '20 at 13:21
  • As the answers say, `double(myInt)` and `(double)myInt` mean the same thing. But with `long double` they're not the same. – Pete Becker Feb 13 '20 at 14:49

2 Answers2

5

Is there a difference between (double)myInt and double(myInt) in c++?

Only difference is syntactical. The meaning is the same.

The latter "functional" syntax cannot be used with compound types: int*(x) does not work.

eerorika
  • 232,697
  • 12
  • 197
  • 326
2

(double)myInt is type conversion from int to double. In modern C++, it is strongly advised to use static_cast<double>(myInt).

double(myInt) calls double's "constructor" which also does the type conversion.

Essentially, they are the same and will result in the same ASM output.

Check the following code:

#include <iostream>

int main() {
    int a = 5;

    double b(a);           // line 1
    double c = (double)a;  // line 2

    return 0;
}

Both lines result with the same ASM:

cvtsi2sd        xmm0, DWORD PTR [rbp-4]
movsd   QWORD PTR [rbp-24], xmm0

Check here

NutCracker
  • 11,485
  • 4
  • 44
  • 68
  • Compiler Explorer is a nice tool thank you for your link. Are you sure, that `double(myInt)` calls a constructor. I always thought that constructors only exists for classes. And in c++ double is not a class is it? – NelDav Feb 13 '20 at 13:35
  • 1
    @NelDav built-in types like `double` don't have constructors but this type of [value initialization](https://en.cppreference.com/w/cpp/language/value_initialization) reminds on constructor. Check another answer [here](https://stackoverflow.com/a/5113429/5517378) – NutCracker Feb 13 '20 at 13:38