Search code examples
cc99complex-numbers

C99 complex casting


I have some C99 code where I need to convert an array of 2n double to an array of n double complex. I do this with

static void real_to_complex(const double *r, size_t n, double complex *z)
{
  size_t i;

  for (i=0 ; i<n ; i++)
    z[i] = r[2*i] + r[2*i + 1]*I;
}

This is a performance critical part of the code, and I'd really rather not have to create a new storage area z and have the expense of the copying, instead I'd like to replace these function calls by

z = (double complex*)r;

Is there any way to do this and remain standard conforming? I understand that a double complex is guaranteed to have the same layout as an array of two doubles -- perhaps I could get away with a compiler check as to whether this layout is (real,imaginary) or (imaginary,real)?


Solution

  • You are guaranteed the first element of the complex array corresponds to the real part and the second element corresponds to the imaginary part.

    Quote from the publicly available draft of C11 Standard

    6.2.5/13 Each complex type has the same representation and alignment requirements as an array type containing exactly two elements of the corresponding real type; the first element is equal to the real part, and the second element to the imaginary part, of the complex number.

    Example program

    #include <complex.h>
    #include <stdio.h>
    
    int main(void) {
      double x[] = {42, 2, 41, 1, 0, 0};
      _Complex double *y = (void*)x;
      while (creal(*y) > 0) {
        printf("%f + %fi\n", creal(*y), cimag(*y));
        y++;
      }
      return 0;
    }