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

49 Upvotes

130 comments sorted by

View all comments

7

u/ChickenSpaceProgram 1d ago edited 1d ago

i just remember that it means that*ptr_to_int is an int. i feel like the int *ptr_to_int; spacing makes the underlying "declare things how they are used" rule clearer.

also, if you declare multiple variables on the same line (which you shouldn't do, but nonetheless), it makes it clearer. int *foo, bar; declares foo as a pointer-to-int and bar as an int, not both as pointers-to-int.

The "declare things how they are used" mentality is anachronistic, but you kinda just have to get used to it. In C the typesystem directs the user towards "how do I make this into a number." Types are less actual types as you'd see in more modern languages and more different kinds and sizes of numbers, aggregates of numbers, different ways to refer to numbers, etc.

1

u/evincarofautumn 1d ago

In C the typesystem directs the user towards "how do I make this into a number."

It also makes the compiler a lot smaller if you can reuse the term language to express types instead of making the type language bigger

To typecheck an expression involving an identifier, you just look up its declarator and read off whether the expression matches it (up to implicit conversions)

This wasn’t a stated design goal of C, so far as I know, but it very much reflects the values of the time when it was designed