http://gcc.gnu.org/bugzilla/show_bug.cgi?id=48956

--- Comment #4 from stevenj at alum dot mit.edu 2011-05-11 20:16:57 UTC ---
Created attachment 24230
  --> http://gcc.gnu.org/bugzilla/attachment.cgi?id=24230
patch to add a -Wconversion warning for complex -> real conversions

I believe the attached patch (against gcc 4.6.0) implements the feature I
requested.  It emits a warning for implicit conversions of complex types to
real (or integer) types.  It also emits a warning for similarly converting
complex constants, unless the imaginary part of the constant is zero in which
case it is treated as a real (or integer) constant given by the real part.

Note that complex->complex conversions are still not checked (e.g. no warning
is given in converting a complex double to a complex float, etcetera), but at
least I didn't add any regressions in that regard.

For example, when compiling the following test file:

#include <complex.h>
#include <math.h>

double foo(double complex z)
{
     complex double zc = 1 + 1i;
     complex double zc0 = 1 + 0i;

     float complex zf = z;

     double x = z;
     float xf = z;
     int i = z;

     double xc = 1 + 1i;
     double xc0 = 1 + 0i;
     int ic = 1.1 + 1.1i;
     int ic0 = 1.1 + 0.0i;

     return sqrt(z) + csqrt(z);
}

with "gcc -Wconversion -c", the unpatched gcc gives no warnings whereas the
patched gcc emits:

complex-Wconversion-tst.c: In function ‘foo’:
complex-Wconversion-tst.c:11:6: warning: conversion to ‘double’ from ‘complex
double’ may alter its value [-Wconversion]
complex-Wconversion-tst.c:12:6: warning: conversion to ‘float’ from ‘complex
double’ may alter its value [-Wconversion]
complex-Wconversion-tst.c:13:6: warning: conversion to ‘int’ from ‘complex
double’ may alter its value [-Wconversion]
complex-Wconversion-tst.c:15:6: warning: conversion to ‘double’ alters ‘complex
int’ constant value [-Wconversion]
complex-Wconversion-tst.c:17:6: warning: conversion to ‘int’ alters ‘complex
double’ constant value [-Wconversion]
complex-Wconversion-tst.c:18:6: warning: conversion to ‘int’ alters ‘double’
constant value [-Wconversion]
complex-Wconversion-tst.c:20:6: warning: conversion to ‘double’ from ‘complex
double’ may alter its value [-Wconversion]
complex-Wconversion-tst.c:20:21: warning: conversion to ‘double’ from ‘complex
double’ may alter its value [-Wconversion]

Note that two warnings are emitted for the last line: one for the implicit
conversion of z to a real number in sqrt(z), and the other for the implicit
conversion of the complex sqrt(z)+csqrt(z) to a real return value of foo(z).

Using creal(...) and/or explicit casts silences the warnings.  Note also that
"double xc0 = 1 + 0i;" correctly yields no warning.

As mentioned above, "float complex zf = z;" and similar complex->complex
conversions probably should emit a warning, but I have not implemented that. 
However, that is not a regression.

--SGJ

Reply via email to