What is the _Complex keyword in C?

Have you ever think how to write and use the complex number in C?  If you have thought, you can write in the comment box where you have used it. But if you have not thought, then don’t worry in this blog you will learn how to write and use complex numbers in C.

In C, we use _Complex keyword to declare a complex number. In mathematics, a complex number is an element of a number system that contains the real numbers and a specific element denoted i, called the imaginary unit, and satisfying the equation i2 = −1.

Each complex number can be expressed in the form a + bi,  where a and b are real numbers and a is called the real part, and b is called the imaginary part.

_Complex in C

What is _Complex keyword in C?

_Complex keyword is a type specifier. You should not use it if the implementation does not support complex types. There are three complex types, designated as float _Complex, double _Complex, and long double _Complex.

C99 introduces <complex.h> header. The header <complex.h> defines macros and declares functions that support complex arithmetic. If you include this header file, the above three types can be represented as the below types because complex expands to _Complex.

  1. float complex
  2. double complex
  3. long double complex

 

Some Important macro of <complex.h>

Note: imaginary and _Imaginary_I are defined if and only if the implementation supports imaginary types.

Macro Name Expands To
complex _Complex
imaginary _Imaginary
_Complex_I (const float _Complex) i
_Imaginary_I (const float _Imaginary) i
I _Imaginary_I(_Complex_I if _Imaginary_I is not defined,)

 

Example code of _Complex keyword in C:

In the below code, we are declaring two complex numbers z1 and z2. We are performing arithmetic operations on both complex numbers and printing the real and imaginary parts of both resultant numbers.

We used the creal() function to get the real part and cimag() function to get the imaginary part of a complex number.

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


int main()
{
    //declaring a complex number using complex
    double complex z1 = 1 + 2*I;

    //Arithmetic operation of complex number
    z1 = 3 * z1;

    printf("3 * (1.0+2.0i) = %.1f%+.1fi\n", creal(z1), cimag(z1));

    //declaring a complex number using _Complex
    double _Complex z2 = 1 + 2*I;

    //Arithmetic operation
    z2 = 1 / z2;

    printf("1/(1.0+2.0i) = %.1f%+.1fi\n", creal(z2), cimag(z2));

    return 0;
}

Output:

3 * (1.0+2.0i) = 3.0+6.0i
1/(1.0+2.0i) = 0.2-0.4i

 

Recommended Articles for you: