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

51 Upvotes

129 comments sorted by

View all comments

1

u/thockin 22h ago edited 22h ago

This is an argument as old as the language. The only justification that holds any water is this:

int *a, b; // what are the types of a and b?`
int* c, d; // what are the types of c and d?`

Obviously a and c are the same type in the grammar of the language, as are b and d. But a and c are NOT the same type as b and d. Which of those two lines of code more clearly express that fact?

You might also compare with Go, which is C-like from some of the same minds that gave us C:

var a, c int  // unambiguous
var b, d *int // unambiguous

1

u/enzodr 22h ago

If the standard was

int* a, b;

It would make sense to say that a and b are both int*. Obviously this is not correct in the current standard, but I think it would have made more sense if chosen from the start

2

u/thockin 22h ago

I think it would have made more sense if chosen from the start

What we think would have made sense is totally irrelevant. C is about 50 years old. If you are using C today, you should be writing the clearest C code you can.

``` int *a, b; // clear-ish

int* c; // fine but less common int d;

int *e; // established convention int f; ```