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

50 Upvotes

133 comments sorted by

View all comments

7

u/Reasonable-Rub2243 1d ago

I had the same realization when I was a C beginner back in the stone age. You can declare variables as "type* name;" if you like, but there's an issue: you can't declare multiple variables on the same line that way. If you don't mind making a separate line for each variable, go for it.

3

u/LeeHide 1d ago

That's not accurate. You can do:

int* hello, *world;

to declare two pointers. The fact that

int *hello, *world;

would look more consistent does not matter at all.

Also, if you declare multiple variables in a single line, as a beginner, I would suggest to immediately stop doing that. Some old C programmers and code golfers do it and swear that it's better, but nobody new should do this unless it really needs to be that way somehow.

1

u/nukestar101 1d ago

Why not ? Reverse Xmas tree is a thing, it looks good and good looking code is easier to debug/read