Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing std::complex

Tags:

c++

I saw couple of examples online which shows that the std::complex variables can be initialized by the following:

std::complex<float> val(10, -2);

But, is there a way to do something like the following:

std::complex<float> val;
val.real = 10;
val.imag = -2;
like image 598
veda Avatar asked Dec 16 '22 13:12

veda


1 Answers

std::complex::real and std::complex::imag are acutally functions. They can be used to either return the real / imaginary part as well as to set them, but still using the function call syntax by providing the value as an argument:

std::complex<float> val;
val.real(10);
val.imag(-2);

However, this is not called initialization. This changes the value of val, which has been initialized in the very first line of code with zero.

Effectively, you see the same result (after that code, val has the value you expect it to be), but requires some more instructions unless the compiler can optimize this away. Since std::complex is a standard type it's very good possible that the compiler will do that, but you can never be sure about this.

like image 88
leemes Avatar answered Dec 26 '22 20:12

leemes