3
#define int_p int* int_p p1,p2,p3; // only p1 is a pointer ! 

can somebody exlplain why it is so.

2

3 Answers 3

14

#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.

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

Comments

2

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.

Comments

1

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:

  1. Do it all by hand:
     int *p1, *p2, *p3; 
  2. Use your macro, but use multiple declarations
     int_p p1; int_p p2; int_p p3; 
  3. 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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.