sandeep said:
Hi,
when accessing the variables in a struct: What's the reason why in C
you have -> and . instead of only . ? Are there cases in which the
compiler couldn't figure out what to do? The problems are
1) extra typing
2) inconsistency with other languages Java, Ruby etc.
(obviously Java came later but it would be good to converge to standard
usage for accessing members)
Given:
point p = {10,20,30};
point *q = &p;
point **r = &q;
point ***s = &r;
the way to dereference these would be something like:
printf("p.y = %d\n",p.y);
printf("q.y = %d\n",(*q).y);
printf("r.y = %d\n",(**r).y);
printf("s.y = %d\n",(***s).y);
Notice the pattern emerging. Now introduce "->", and the pattern looks like:
printf("p.y = %d\n",p.y);
printf("q.y = %d\n",q->y);
printf("r.y = %d\n",(*r)->y);
printf("s.y = %d\n",(**s)->y);
So not quite so orthogonal. Now what would this look like if "." and "->"
were interchangeable?
Either:
printf("p.y = %d\n",p.y);
printf("q.y = %d\n",q.y);
printf("r.y = %d\n",(*r).y);
printf("s.y = %d\n",(**s).y);
in which case this doesn't buy you much in the general case (but matches how
arrays work, where 0 or 1 levels of indirection have the same syntax; more
need extra derefs); or:
printf("p.y = %d\n",p.y);
printf("q.y = %d\n",q.y);
printf("r.y = %d\n",r.y);
printf("s.y = %d\n",s.y);
which is certainly neater, but having "s.y" hiding 3 levels of indirection
would introduce it's own problems I think.
(And would no match the way arrays work, by having all indirection levels
have the same syntax instead of just 0 and 1 levels. I wasn't able to check
function indirection because I can never remember the syntax for function
pointers; if new syntax is called for, that might be a better place to
start...))
One problem is that "->" is quite an ugly, bolted-on construct and does not
really follow on from the ".". Using Pascal syntax for "." and "->", my
example would look like:
printf("p.y = %d\n",p.y);
printf("q.y = %d\n",q^.y);
printf("r.y = %d\n",r^^.y);
printf("s.y = %d\n",s^^^.y);
which I think is an improvement on any of the C variations, existing or
planned: looks reasonable and gives the important distinction between the
values.