When declaring pointers in C, there are 3 variants:
Variant A:
int* ptr;
Variant B:
int *ptr;
Variant C:
int * ptr;
The way a pointer is declared differs depending on the type of documentation I read. Some authors seem to have a preference for certain variants, others use several.
The syntax of declaring a pointer is to place a * in front of the name. A pointer is associated with a type (such as int and double) too. Naming Convention of Pointers: Include a "p" or "ptr" as prefix or suffix, e.g., iPtr, numberPtr, pNumber, pStudent.
A pointer declaration names a pointer variable and specifies the type of the object to which the variable points. A variable declared as a pointer holds a memory address.
The first character of the name should be a letter and all characters (except the period) should be lower-case letters and numbers. The base name should be eight or fewer characters and the suffix should be three or fewer characters (four, if you include the period).
The syntax for declaring a pointer array is the following: dataType *variableName[size]; /* Examples */ int *example1[5]; char *example2[8]; Following the operators precedence, the first example can be read as - example1 is an array( [] ) of 5 pointers to int . Similarly, example2 is an array of 8 pointers to char .
Something nobody else has mentioned is that
int *ptr;
corresponds more closely to the language grammar.
int *ptr;
is a declaration, which consists of: int
, followed by*ptr
.(That actually skips a number of steps, but it gets the basic idea across.)
Since declaration follows use, what this means is that *ptr
is of type int
. It follows from this that ptr
is of type int*
.
One could argue that this makes it better than
int* ptr;
for the same reason that
x = y+z;
is better than
x=y + z;
Of course you can write
int* ptr;
and read it as "ptr
is of type int*
". And plenty of programmers do exactly that, and get along just fine (it tends to be the preferred style in C++). The compiler doesn't care which way you do it, and anyone reading your code shouldn't have trouble understanding it either way.
But whichever spacing you choose, you need to understand what int *ptr;
really means, so that when you see
int *ptr, i;
in someone else's code (as you inevitably will), you'll immediately understand that ptr
is a pointer and i
is an int.
And if you're working with other programmers on a project, you should follow whatever existing convention is in the coding standards, or if there isn't one, the way the code is already written. I personally prefer int *ptr;
to int* ptr;
, but using a mixture of both styles is far worse than using either one consistently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With