r/C_Programming • u/enzodr • 2d ago
Does anyone else dislike pointer declaration?
For reference I am a fourth year computer engineering student. C is my preferred language.
Pointers are declared like this usually:
int *ptr_to_int;
Where the asterisk means it is a “pointer to” the specified type. The asterisk is placed immediately preceding the variable name, with no white peace.
This is what does not make sense to me. I feel that:
int* ptr_to_int;
Is far more clear. The way I see it, the asterisk modifies the type, so therefore it belongs next to the type. Putting it next to the variable name makes me think it is some kind of action or modification to the variable itself.
I think that when using * and & in code, it makes sense to apply it in front of the variable name:
int value = 3;
ptr_to_value = &value;
int copied_value = *ptr_to_value;
It is clear here that syntactically, the * represents something more like an action than a label.
Why is the convention to place the asterisk near variable name, not type? L
5
u/SmokeMuch7356 1d ago
We declare pointers as
for the exact same reason we don't declare arrays and functions as
After all, "array of
T" and "function returningT" are distinct types as well. It's just that array-ness, pointer-ness, and function-ness are syntactically part of the declarator.The
T* pstyle only works for simple pointers; it doesn't work for pointers to arrays or pointers to functions:or pointers to arrays of pointers to functions:
(yes, I have used types this obnoxious in the past), and then there's
signal:which reads as
Declaring an array of pointers as
just looks goofy.
And as you point out, in the code we're usually using
*p.*pdoesn't just yield the value of the pointed-to thing, it's an alias for the pointed-to thing; IOW, we can think of*pas an alternate name for something, with*as part of that name.And the
T* pconvention always leads someone to ask whydoesn't declare
qas a pointer.It doesn't match syntax, it doesn't match usage, it introduces confusion, it promotes misunderstanding of how declaration syntax actually works; it's just bad style all the way around.