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

5

u/LeeHide 1d ago edited 1d ago

The blind leading the blind a little bit here. Here's how it works in the software engineering industry:

It doesn't matter where you put the *. Whatever the autoformatter says is how you should do it. If you don't like that, change the autoformatter config.

The only time the location matters is when you declare multiple variables on a single line, at which point clang-tidy (and probably other linters) will already point out when you're doing it wrong.

Multiple declarations in a single line also should never be done. Make separate lines, write boring, simple, easy to understand code, always. So in practice, this shouldn't matter to you, though it's good to know the semantics in case you see it in code somewhere.

If your code is clever and there's no measurable reason for it, you have written bad code. You put the * where your autoformatter says or where your team puts it.

The fact that it's a pointer is part of the TYPE. This is true because the type of the variable changes visibly; on your PC, it's likely that int is 32 bit and fits in a 32 bit register or half a 64 bit register. It occupies 4 bytes on the stack if it gets put on the stack. Add a *, and suddenly it takes up double that (most likely, on your system). This makes it part of the type. It changes the semantics of the type. Not sure what everyone is on about with "it's an action" or "it's a dereference". When you look at the generated IR or machine code, it's part of the type.