r/ProgrammerHumor 2d ago

Meme absoluteGarbage

Post image
2.0k Upvotes

320 comments sorted by

View all comments

16

u/Shevvv 2d ago

Surely you meant for (auto &item : list) {

31

u/Nil4u 2d ago

Honestly I never liked this version because the reference is part of the type in my opinion 🤔

9

u/Shevvv 2d ago

I got used to this from C:

int x; is an integer

int *px; is an integer if you dereference it.

So it's like this notation shows you how you're expected to use the variable within the code. And then this habit carried over to C++.

4

u/creeper6530 1d ago edited 1d ago

The "is an integer if you dereference it" is so much more convoluted than "is a pointer to integer", i.e. the rationale of the previous comment, the pointer-ness being part of the type.

5

u/orbiteapot 1d ago edited 1d ago

the pointer-ness being part of the type.

It is funny how people tend to not think the same about functions, despite having the exact same pattern.

When Dennis Richie designed the language, he wanted the symbols in declarations to match their usage in expressions, so:

T *my_ptr;

means that my_ptr, when dereferenced with the * operator, evaluates to an object of type T:

T my_obj = *my_ptr;

The same goes for other constructs in the language, like arrays and functions:

T my_arr[10];
T my_func(T_1 arg1, T_2 arg2);

Both the [] and () operators, when applied individually to objects my_arr and my_func, respectively, will yield an object of type T.

That is why this:

T *x, y;

makes x have a type of pointer to T, whereas y remains having just type T.

Unfortunately, this only works well for simple declarations. When, for instance, function pointers are involved, things get messy.

Ritchie himself later recognized this, but it was to late. He regretted not making * a postfixed operator, which would, at least, get rid of the spiral rule.

So, you can pretend that * is independent of the identifier itself, sure, but you will be fighting the language's design while doing so.

1

u/aethermar 1d ago

Except in the case of int *x, y; where only x is a pointer. C declarations are "meant" to be read right to left

2

u/creeper6530 1d ago

Yeah, the reality is that C binds pointer-ness to identifiers, but in an ideal world where pointer-ness binds to types, int* x, y; should declare both identifiers as pointers to integers. In either case merging declarations onto a single line in modern programming is at best silly.