0

I'm learning to build complex types. Here I defined a pointer to an array 5 of shorst using typedef:

typedef short (*mytype)[5];

I'm trying to find out how to to the same with the #define directive and if it is even feasible. I tried this, but it does not work:

#define MYTYPE (short*)[5]

It seems like this directive cannot be applied for defining something more complex than a pointer or a struct. So, what is the point here?

7
  • 1
    Suggestion: don't hide * behing a typedef. The * in source code is a good visual note about something being a pointer; in the same way, the absence of * is a good indicator something is not a pointer. Hiding the * in a typedef breaks this visual indication. Commented Oct 22, 2020 at 20:14
  • @pmg I only seek educational purposes, this is not of any practical use. Still thanks for the piece of advice, I'll keep that in mind Commented Oct 22, 2020 at 20:15
  • 1
    The type would be short (*)[5], but that would only be good in certain contexts, such as casts or sizeof operands, not for declarations. #define directives are not particularly for creating aliases for types. Appropriate uses include very short “functions”, providing some substitutions that are useful for customizing software to various environments, or signaling features to turn on/off. Commented Oct 22, 2020 at 20:15
  • @EricPostpischil does not work, when specifying MYTYPE var; it asks for an identifier or ( Commented Oct 22, 2020 at 20:20
  • @Kaiyaha: As my comment says, it is not good for declarations. And as my comment says, #define directives are not for creating aliases for types. Commented Oct 22, 2020 at 20:20

1 Answer 1

1

How to define a [variable of a pointer to array type] with the #define directive?

You may just use a function macro.

#define MYTYPE(name)  short (*name)[5]
int main() {
    short arr[5];
    MYTYPE(a) = &arr;
    typedef MYTYPE(mytype);
}

what is the point here?

There's is no point - preprocessor is a string replacement tool that is generally not aware of C syntax. Use a typedef to define an alias for a type.

Sign up to request clarification or add additional context in comments.

2 Comments

Well, that was the most obvious solution, but I just wanted MYTYPE to look exactly like a regular type. Is that possible?
plak plak plak :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.