Reputation: 2002
If I write something like
#define INT_PTR int*
INT_PTR ptr4, ptr5, ptr6;
In this case only ptr4 is pointer to an integer, rest of the values (ptr5 and ptr6) are integers. How they are taking the integer value ? Either it should give some compilation error.
Why is it this way that compiler is treating ptr5 and ptr6 as integers.
Upvotes: 2
Views: 119
Reputation: 882726
This actually has nothing to do with the #define
, which is simply a textual replacement.
After the preprocessor phase (when the substitution takes place), you end up with:
int* ptr4, ptr5, ptr6;
and, because the *
binds to the variable rather than the type, you create one integer pointer and two integers.
This is why I prefer to write:
int *xyzzy;
rather than:
int* xyzzy;
since the former makes it clearer that the *
belongs to the variable. If you want to define a new type in C, the command is, surprisingly enough, typedef
:-)
typedef int * INTPTR;
INTPTR ptr4, ptr5, ptr6;
That defines a new type that will apply to all variables that follow it, rather than just substituting text, as per the macro. In other words, the type INTPTR
(int *
) applies to all three of ptr4
, ptr5
and ptr6
.
Upvotes: 4
Reputation:
Your code expands to
int* ptr4, ptr5, ptr6;
And since the asterisk (*) declaration is applied to only the identifier follwing it, it's natural that only ptr4 will actually be a pointer. (By the way, that's why it's conceptually wrong to write
int* ptr;
as you should indicate that the pointer declaration is only for one variable, as such:
int *ptr.
)
So, instead of a #define
preprocessor directive (which is also wrong for type definitions), use the C typedef
keyword:
typedef int *inptr;
intptr ptr4, ptr5, ptr6;
Upvotes: 1
Reputation: 145919
Because to declare pointer objects you would do:
int *ptr4, *ptr5, *ptr6;
In C, the token *
does not belong to the type information, so you have to repeat it when you declare several objects. Note that this is a frequent mistake in C.
What you can do is to typedef
instead:
typedef int * INTPTR;
Upvotes: 11