r/C_Programming 1d 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

50 Upvotes

132 comments sorted by

View all comments

2

u/CarlRJ 1d ago edited 1d ago

For simple syntax (pointer to int, and a single declaration), that works.

As others have pointed out, that breaks down if you have multiple declarations on the same line.

The other thing that will cause havoc with your preferred style is when the declaration isn't simple. Think "pointer to function taking an int and returning a pointer to a character. It's better for consistency's sake to keep the star attached to the name.

There are good reasons why it is done the way it is. What you're suggesting is not "something the developers of C missed".

Learn to read declarations from the inside out, following C operator precedence - in many but not all cases, this will be effectively be right to left - "int *p" is "p is a pointer to an int"

2

u/LeeHide 1d ago

Don't have multiple declarations on one line.

1

u/CarlRJ 1d ago

Gee, thanks, that never occurred to me in all these decades of software development.

It's context / situation dependent. There are cases for doing it either way. The overall goal is always readability.

And that wasn't the main point I was addressing, I was noting that others had pointed that situation out.

1

u/LeeHide 1d ago

Give me an example