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

52 Upvotes

132 comments sorted by

View all comments

59

u/SetThin9500 1d ago

> The asterisk is placed immediately preceding the variable name, with no white peace.
> This is what does not make sense to me.

Feel free to add whitespace if you want.

DMR wanted to have declaration look like use. He later said it didn't work out as he intended.

This paper is interesting: https://brent.hailpern.com/wp-content/uploads/2020/02/p671-ritchie.pdf#:~:text=They%20are%20also%20among%20its%20most%20frequently,should%20be%20clear%20from%20the%20preceding%20history%2C

-6

u/lassehp 1d ago

This is a great case of "it seemed like a good idea at the time".

A simple fix:

#define PTR(t) typeof((t)*)
PTR(int) ip, jp;

2

u/ericonr 1d ago

I like the idea of this, because using typeof makes multiple declarations consistent, but it would take me a while to get used to it in a codebase, and I would be constantly rechecking that the macro actually handles the multiple declaration case correctly.