Does casting a real number to complex number set imaginary part to 0 in C?
Asked Answered
A

2

6

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) ?

Astound answered 3/8, 2022 at 22:44 Comment(2)
Yes. What else would it be meaningful to set it to?Mong
@Mong "What else" --> C could have allowed negative values get an imaginary part of -0.0. Interesting that C specifies for implementations with signed zero and the sign-less zero.Unsuccessful
F
7

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.

Farra answered 3/8, 2022 at 23:11 Comment(2)
Convert <> cast.Kayak
@Kayak From the beginning of 6.3 section: "This subclause specifies the result required from such an implicit conversion, as well as those that result from a cast operation (an explicit conversion)."Manassas
B
1

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

Beatrisbeatrisa answered 3/8, 2022 at 23:11 Comment(2)
Convert <> cast.Kayak
@philipxy, a cast is one way to perform a conversion (but not the only one). So although it is true that "convert" is not identical to "cast" in this context, the behavior of the cast in question is governed by the rules for conversions.Laudianism

© 2022 - 2024 — McMap. All rights reserved.