Where to place astric when declaring pointer


In C, when you’re declaring a pointer, does it matter if you place the astrix to the pointer name like book_t *ptr; or beside the type book_t* ptr;. Which is the perferred syntax?

#include <stdio.h>
typedef struct Book
 char name[10];
 int price;
} book_t;

int main()

 book_t data; //Single structure variable

 book_t* ptr; //Pointer of Structure type

 ptr = &data;

The best place for it is with the variable name.
If you're in the habit of declaring multiple variables with a single type-specifier, this int* pointerA, pointerB;
may look like you're defining two int pointers, but you're not.

I would of thought this is two int pointers? You definitely have a pointerA of type int but what is pointerB?

"pointerB" is an int.

Ah yes, because * binds to the right and not the left.



Another interesting view on this is if we take the original:
int* pointerA, pointerB;

and swap the first and second variables, we would get this:
int pointerB, *pointerA;

and that is perfectly valid and easier to read, and takes away any possible misconception of what might be meant for the two variables. It's now clear as day that pointer B cant be a pointer, really.

Also interesting but i've never tried is:
(int*) pointerA, pointerB;

if the compiler even accepts this, it might be confusing also, but if it does accept it i would think there would be no difference, that pointerB is still NOT a true pointer.

There are some tricks though, as later it may be possible to cast it into a pointer if it is the right type to be promoted in the first place. Probably not the best idea though.

If anyone wants to try that "(int*) A,B" thing, and test each var to see if it really became a pointer, that would be cool :slight_smile:

BTW, it's called an "asterisk".

Also maybe try:
int* (A,B);

int* {A,B};