Document: WG14 N1464


Creation of complex value


Submitter: Fred J. Tydeman (USA)
Submission Date: 2010-05-10
Related documents: N818, SC22WG14.8195, N1399, N1419, N1431
Subject: Creation of complex value

Problem: (x + y*I) will NOT do the right thing if "I" is complex and "y" is NaN or infinity. It does work fine if "I" is imaginary. Users and library implementors have noticed this deficiency in the standard and have been surprised that there is no easy to use portable way to create a complex number that can be used in both assignment and static initialization.

WG14 paper N818 presented more details on why the problem exists as well as many possible solutions. Papers N1419 and N1431 added some more possible solutions.

Proposal

This has been shipping for several years from HP.

Add 3 new function-like macros to <complex.h> in section 7.3.9 Manipulation functions:

7.3.9.x The CMPLX macros

Synopsis

#include <complex.h>
  double      complex CMPLX( double x, double y ); 
  float       complex CMPLXF( float x, float y );
  long double complex CMPLXL( long double x, long double y ); 

Description

The function-like macros CMPLX(x,y), CMPLXF(x,y), and CMPLXL(x,y) each expands to an expression of the specified complex type, with real part having the value of x (converted) and imaginary part having the value of y (converted). Each macro can be used for static initialization if and only if both x and y could be used as static initializers for the corresponding real type.

The macros act "as if" an implementation supports imaginary and the macros were defined as:

#define CMPLX(x,y) ((double)(x)+_Imaginary_I*(double)(y))
#define CMPLXF(x,y) ((float)(x)+_Imaginary_I*(float)(y))
#define CMPLXL(x,y) ((long double)(x)+_Imaginary_I*(long double)(y))

Returns

The CMPLX macros return the complex value x + i*y created from a pair of real values, x and y.

Add to the rationale in the section on complex:

x + y*I will not create the expected value x + iy if I is complex and "y" is a NaN or an infinity; however, the expected value will be created if I is imaginary. Because of this, CMPLX(x,y) as an initializer of a complex object was added to C1x to allow a way to create a complex number from a pair of real values.