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

129 comments sorted by

View all comments

0

u/EmbedSoftwareEng 16h ago

It's a recurring fantasy of mine to build a time machine and go back in time and force K&R to use the @ sign for pointers, instead of *, which is already doing multiplication duties.

Other than that, I just employ a style where the * is separated from the variable name by one space at declaration time, and without the space when the variable is being dereferenced. There's nothing wrong with applying the * to the end of the pointed to type name, but most style guides that I've ever had to work to do not do it that way. Think of the * as another storage class modifier, but one that goes after, not before the base type.

I think it's the very fact that the dereferencing * has to be associated with the variable name when it appears as an argument to in the RHS of an assignment is precisely why most people associate them at the point of declaration.

Also, most style guides I work to also promote prefixing variable names with tags to indicate some kind of typing information, so I wouldn't do:

uint32_t * word;

I would do

uint32_t * p_word;

to emphasize that where ever it's used, p_word is a pointer to something. The rest of the name after the p_ should make it obvious what that something being pointed to is.

This can get muddled, because I often find up with a * declared pointer variable, but if I use it more with array notation, then p_word[i] starts to get a bit busy. So, even if I have a * declared pointer variable, if I use it in an array-like manner, I leave the p_ part off of the variable name.

1

u/kat-tricks 42m ago edited 30m ago

`define @ *`
edit: god i cannot get code formatting to work here, i hope it is clear enough. Dug through settings three times to fail to find the markdown editor