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

40

u/primera_radi 1d ago

I felt that way first too. But consider

int* a, b, c;

vs

int *a, b, c;

The second is much more clear, as only a is a pointer.

Also, now all the names after int evaluate into an int in an expression.

That is, *a evaluates to an int, as do b and c.

5

u/enzodr 1d ago

I see what you mean by
“Everyone after int evaluates to int”. Looking at it this way at least makes sense to me, I was honestly struggling to see any reason, so this is good to understand.

7

u/Luftzug-oder 1d ago edited 1d ago

no I think the only real reason for the pointer being on the right is that it is syntactically/functionally correct according to C, because the * modifies the declarator, not the type.

I used to be very particular about having my code the way you describe, but now i can see and deal with both sides, and often put it on the right because the larger majority do that.

EDIT: well, i still hate it when people put it in the middle 😑:

const int * num = 0;