Reputation: 3
I am bit new to C language and I have a question in some basic principles about C. I'm on the way of implementing a custom complex library that deals with fixed point arithmetic.
We can use a library called complex.h in C. using that library we can declare and initialize complex variable as below.
complex float a = 2 + 3I;
complex float b = 5 + 2I;
complex float c = a + b;
but when we adding this two complex float, how does the compiler understand that we are going to add two complex numbers. Does the compiler understand it using its data type?
Then what is the approach that we need to follow implement a data type like complex?
I already know how to implement that using structures. But I need to know about how I make that structure to deal with a variable given in the format of a + bI
.
To be more clear my question is how I deal with that 'I' character inside my Structure?
Upvotes: 0
Views: 295
Reputation: 96091
In C, the complex types are built into the language itself. Including <complex.h>
merely lets you use the word complex
to work with them; without the header you have to spell it out as _Complex
.1 The complex types are built into the language, so the compiler has innate knowledge of them. You can't create similar types on your own.
In C++ (which the question was originially tagged with), std::complex
from <complex>
is a class. +
and some other operators work with it because they are overloaded for it. There's nothing magical about this, and you can make your own classes that behave in this way. Unlike C++, C doesn't have operator overloading, so it's not possible in C.
1 This was done to preserve backwards compatibility with programs that use the word complex
for other purposes. Words starting with _
followed by an uppercase letter are reserved, so it was illegal for programs to use the word _Complex
for any purpose before the complex numbers were introduced into the language.
Upvotes: 3
Reputation: 223739
The compiler knows how to handle performing arithmetic on complex
types. You can then use the functions crealf
and cimagf
(or creal
and cimag
for complex double
) to get each part.
complex float a = 2 + 3I; complex float b = 5 + 2I;
complex float c = a + b;
printf("result: %f%+fi\n", crealf(c), cimagf(c));
Output:
7.000000+5.000000i
Upvotes: 0