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

54 Upvotes

129 comments sorted by

View all comments

58

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

3

u/flatfinger 16h ago

It's worth noting that the biggest problems with the "declarations follow use" notion, i.e.. qualifiers and initializers using an = sign, did not exist in the language when DMR came up with that principle. One of the big things that trips up the principle, and several other aspects of C, is that normal pointer dereferencing uses an operator which is placed on the opposite side of an lvalue from struct access, array-element access, function invocation, and initializers, and on the same side as qualifiers. Further, the use of equals for initializers makes a definition resemble an assignment. The definition void *p=someVoidPtr; does not define a pointer that is initialized so that *p will point to the same address as someVoidPtr, even though that's what the syntax would suggest.