C++ and Complex Numbers

Perhaps the most important thing to say about C++ and complex numbers is that it is not the same as C99. Indeed, it is so different that C99 programs using complex numbers will not compile with a C++ compiler. The often-heard claim that C++ is a superset of C is thus proven false.

Like most languages, it is capable of surprises.

#include <complex>
#include <iostream>

int main(){
  using namespace std;
  complex<double> z;

  z=2+3i;
  cout << "z=" << z << "\n";
  return 0;
}

The above code contains a deliberate error, and will not compile. Indeed, Gnu's g++ version 13.3 gives me 145 lines of error messages for this.

C++ 14 introduced the idea that a number (integer or real) suffixed by an i is a complex<double> constant with zero real part and imaginary part as given.

But so far no version of the C++ standard allows one to add integers to a complex. So the minimal change to make the above compile with no errors is to change 2+3i to 2.+3i, for adding a real to a complex is defined. The same issue applies to multiplication and division; one cannot mix integers and complex.

Before C++ 14 creating complex constants was less pretty.

  z=complex<double>(2,3);

was one answer, although C++ 11 introduced

  z={2,3};  // Do not confuse with z=(2,3) which sets z=3.

Another way is

  z.real(2);
  z.imag(3);

Unlike C99, there is no predefined constant I. Some may like

typedef std::complex<double> cmplx
#define I cmplx(0.0,1.0)

As for the detail of how C++ performs complex arithmetic, little is said. The storage is compatible with C99, but nowhere does it say that the arithmetic must be too. Many C++ compilers do follow C99 rules, but I see no requirement for them to do so. As nothing is said, just as with Fortran, anything reasonable is permitted. C++ has supported complex numbers since since 1985, long before C99 was approved, so the argument that it must default to following C99 is weak. If C++ compilers do follow C99 Annex G, one must hope that they also have a mechanism for turning this off and restoring performance.