Home > front end >  Does casting a real number to complex number set imaginary part to 0 in C?
Does casting a real number to complex number set imaginary part to 0 in C?

Time:08-05

Does casting a real number to complex number set the imaginary part to 0 in C? Here is what I am trying to do:

#include <complex.h>
#include <stdio.h>

int main(void){

    float complex a;
    double b = 1.0;

    a = (float complex) b ; /* Does this convert to float and set 
                            complex part of a to 0 (according to C standards) ?*/

    a = (float) b ; /* If we also do this, does the compiler set the imaginary part to 0? 
             or we have to explicitly give b   0.0f*I ?*/

    printf("%f \n", cimagf(a));
    return 0;
}

To be more specific, does it leave the imaginary part uninitialised (as a complex number is represented as two reals) ?

CodePudding user response:

Yes, the imaginary portion is set to 0. To quote the C17 standard (draft) section 6.3.1.7:

When a value of real type is converted to a complex type, the real part of the complex result value is determined by the rules of conversion to the corresponding real type and the imaginary part of the complex result value is a positive zero or an unsigned zero.

CodePudding user response:

Yes, converting a floating point value to a complex value sets the imaginary part to 0, as that preserves the value.

From section 6.3.1.7p1 of the C standard regarding Real and Complex conversions:

When a value of real type is converted to a complex type, the real part of the complex result value is determined by the rules of conversion to the corresponding real type and the imaginary part of the complex result value is a positive zero or an unsigned zero

  • Related