peterahrens
peterahrens

Reputation: 88

How does the "complex" macro modify the "double" and "float" types in C?

What preprocessor/compiler magic happens in order to make the declaration:

#include <complex.h>
double complex foo;

resolve to a declaration of a complex double foo?

More specifically, how can I mimic this functionality to create, say, a rabbit type so that I could #include "rabbit.h" and then when I declare:

 double rabbit bar;

bar is declared as a type of my choosing?

Upvotes: 0

Views: 145

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263237

Starting with C99, _Complex is a keyword, part of the core language. Syntactically it's a type specifier, like long or unsigned. It can be used along with any of float, double, or long double.

Thus _Complex double is a type, built into the language.

The standard header <complex.h> defines complex as a macro that expands to _Complex. This is just for convenience. The keyword was given the spelling _Complex to avoid conflicting with valid pre-C99 code; the macro can be used to enable the more common term complex for complex types.

(The C11 standard makes complex types optional.)

There is no language mechanism for defining your own type specifiers.

Upvotes: 4

milleniumbug
milleniumbug

Reputation: 15814

You can't.

You can't make double rabbit x; do something different, the same way you can't make unsigned rabbit x; do that.

_Complex is special cased in the language. There are three complex types: float _Complex, double _Complex, long double _Complex. As you can see, the float/double/long double is the modifier, just like unsigned or long or short are for int.

Upvotes: 2

Related Questions