Addressing struct without ->

Derek R. Foster dfoster at jarthur.Claremont.EDU
Sat Feb 2 10:36:55 AEST 1991


In article <wolfram.665407476 at cip-s02> wolfram at cip-s02.informatik.rwth-aachen.de (Wolfram Roesler) writes:
>NIBMSCM at NDSUVM1.BITNET writes:
>You can however use the preprocessor trick to avoid long chains of -> and .
>in the following way:
>
>#define X ptr->fooptr->foo.bar.bar.baz.foobar->foobaz.x
>
>and now write 
>
>	X->something
>
>instead of (well you know what).

A way that is almost always better is to assign a local, temporary
pointer to the end of that long chain, and then use tempptr->something.
Using this technique, you don't have to dereference multiple pointers
every time you access it. You also don't have the defined macro hanging
around later when you don't want it. (although #undef could be used for
this purpose also.) 

For instance,
in (probably mangled) Pascal:
-----
record ghi
  x,y:integer;
end;
record def
  g:ghi;
end; 
record abc
  d:def;
end;
var jkl : array [0..9] of abc;

BEGIN
  for i:=0 to 9 do
    with jkl[i].d.g do
    begin
      x := 1;
      y := 2;
    end;
END.
-------
in C:
-------
struct ghi {int x,y;};
struct def {ghi g;};
struct abc {def g;};
abc jkl[10];
void main(void)
{
  for (i=0; i<10; i++)
  {
    ghi * temp = & jkl[i].d.g;
    temp->x = 1;
    temp->y = 2;
  }
}

>I'm not sure if the following will work:
>
>struct
>{
>  int foo;
>  int bar;
>} xyz;
>#define foo xyz.foo
>#define bar xyz.bar

Probably not. You've created circular definitions of foo and bar with the
preprocessor. ("foo" expands to "xyz.foo" which expands to "xyz.xyz.foo"
ad infinitum.)

Derek Riippa Foster



More information about the Comp.lang.c mailing list