by jhallenworld · 6y ago · 0 comments
struct foo { int a, b; };
A function that works on the structure looks like this, you use '->': void pr(struct foo *n) { printf("%d %d\n", n->a, n->b); }
But when you make an instance of this structure, you have to use this different syntax: struct foo p;
p.a = 1; // Yuck!
pr(&p); // Bad!
But you can do this instead: struct foo p[1];
p->a = 1; // Very nice..
pr(p); // Yes!Anyway it means you can't cut and paste code from one place to another without changing '.' to '->' or vice-versa.
E.g. a:
int x = a->b->c->d;
means there's 3 memory accesses, while
int x = a.b.c.d;
means there's one memory access for the whole expression.
Also consider this:
int x = a->b.c->d;
I can immediately see where pointer indirections are happening.
...unless you're in C++ of course which messed up this simple rule when references were added to the language.
It's not true if the compiler can figure out that the left side is a constant, consider:
struct foo { int a; };
struct foo z = { 7 };
struct foo *const p = &z;
Then in z->a, no indirection is necessary. GCC -O2 makes this: int fred() { return p->a; }
fred:
movl z(%rip), %eax
ret
p:
.quad z
z:
.long 7Because using `(*ptr).member` everywhere is annoying. There's plenty of times you want or need to have direct access to a member rather than always dereferencing a pointer.