#defi开发者_C百科ne int_p int*
int_p p1,p2,p3; // only p1 is a pointer !
can somebody exlplain why it is so.
#define
is just a textual substitution. The code above is equivalent to
int *p1, p2, p3;
so only p1
is a pointer. You need
typedef int* int_p;
instead.
Rather than thinking of it like this:
int* (p1, p2, p3);
think of it like this:
int (*p1), p2, p3;
As in, only the symbol with the asterisk in-front of it becomes a pointer, not all of them.
Two points:
The preprocessor just does text substitution on the source code before compilation; it has no awareness of types or syntax. After preprocessing, the lines
#define int_p int*
int_p p1, p2, p3;
expand to
int* p1, p2, p3;
Which brings us to our second point; in a declaration, the *
binds to the nearest declarator, not the type specifier; IOW, the above declaration is parsed as
int (*p1), p2, p3;
Whitespace makes no difference; int* p1;
is parsed the same as int *p1;
as int * p1;
.
If you want to declare all three variables as pointers, you have three choices:
- Do it all by hand:
int *p1, *p2, *p3;
- Use your macro, but use multiple declarations
int_p p1; int_p p2; int_p p3;
- Create a type synonym using the `typedef` facility:
typedef int *int_p; int_p p1, p2, p3;
Unlike the preprocessor macro, the typedef is not a simple text substitution; the compiler basically creates a synonym for the type int *
, and that synonym can be used anywhere int *
can be used.
精彩评论