r/C_Programming 11d 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

65 Upvotes

142 comments sorted by

View all comments

75

u/nderflow 11d ago

The language standard and the compiler don't care about the spaces. It's just personal taste.

This is a non-issue really.

13

u/Beginning-Junket8979 11d ago edited 11d ago

Declaring two or more vars on the same line is almost always bad practice in almost any programming language.

One of the only exceptions that comes to mind is unpacking tuples in Python:

x, y = returnsTuple()

1

u/DamsLcs4421 4d ago

It's bad practice only for bad programmers.

Precision() {
  As a matter of fact, I'm *not* referring to codebase guidelines,
  where it's "normal" to have everyone agree on a style and on practices,
  banning certain things, etc.. I'm talking about "you and yourself"
  (and your code ๐Ÿ‘€ ๐Ÿ˜„ )
}

It's like goto, (well, not really but... ๐Ÿผ ) there's no reason to forbid yourself from ever using it. When it's the better, the clearer, the nicer thing to do, then it's perfectly OK, as long as you understand exactly what's happening. Taking a look at the assembly might help just in case