The 1 + 1i
is using a (GCC) extension which creates types similar/equivalent to C99's _Complex int
type. That type is convertible to a real type like int
or double
. std::complex
is not compatible to _Complex
, it does not have any constructors to create a std::complex
from a _Complex
(*). But std::complex<T>
does have a constructor that takes a T
. This triggers the aforementioned conversion _Complex
-> T
-> std::complex<T>
.
So the code in the OP is equivalent to:
#include <complex>
#include <iostream>
int main()
{
double d = 1+1i;
std::complex<double> a = d;
std::cout<<"a ="<<a<<"\n";
return 0;
}
The imaginary part of 1 + 1i
is dropped in the conversion to double
.
To prevent such surprises, try to compile with warnings and -pedantic
. This example seems to be one of the few places where clang actually adds an additional warning with the -pedantic
flag (for gcc, -pedantic
changes the warning output in many contexts):
prog.cc:6:19: warning: imaginary constants are a GNU extension [-Wgnu-imaginary-constant]
double d = 1+1i;
(*) IIRC, std::complex
was introduced in C++98, while _Complex
was introduced in C99.