It's something that I've seen in C and C++ code. It doesn't make sense. I'm going to have a little rant about it.
When you are declaring a pointer, put the asterisk next to the type, because you are modifying the type.
int* x
✔ Yes very good.
int *x
❌ No very bad.
That's it.
The following is my reasoning in more detail for people who need more convincing because they're too stuck in their ways.
If I write int* x
I am writing "x is of type 'pointer to int'".
If I write int *x
I am writing "*x is of type int" which makes no sense.
I know the compiler doesn't care. I could write int*x
and the compiler would eat it up like a good doggy. I care, because I'm reading the code.
*
is not part of the variable name.
If I write x = &intvariable
that is different to writing *x = &intvariable
. The *
is not part of the variable name.
If I have done typedef int* intptr;
and then write intptr *x
I have created a pointer to a pointer to an int, NOT a pointer to an int called *x
.
THE *
IS NOT PART OF THE VARIABLE NAME.
So don't make it look like it is.
Thank you for your time.
You can also understand the asterisk as a prefix on the name to determine that
int *x
asX is a pointer storing a memory address of type int data
or any other argument of your preference. That's the issue, that you can read and interpret it in different ways so it's a bit subjective... 😅I understand that sometimes the notation is confusing, because different textbooks place the * differently. The three following declarations are equivalent:
I always believed that the least confusing notation is
int * x
because when read from right to left you can interpret it asx is a pointer, hence allocating a memory address which references to an int value
, plus you not "link" visibly the asterisk to the type nor to the var name.There are some details into that, see:
This is 1 pointer and 2 int variables.
This is still 1 pointer and 2 int variables.
For the sake of clarity:
Those are effectively 3 pointers and we can understand the asterisk as a somewhat independent (keyword if you will) and use it just like that.
I haven't coded in C for around 10Y, maybe nowadays there is some linter out there that you can use to enforce one way or the other in your projects 😁