🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: gnu.gcc.help
Article #42594

Offsets in structures

#42594
From: Ian Dall
Date: Mon, 13 Nov 1995 00:00
44 lines
1871 bytes
I have a problem where I wish to construct a table to access structure
members. Eg:

    struct state {
      int dummy0;
      int r0, r2;
      int dummy1;
      int r1, r3;
    };


    int read_reg(struct state *t, int regno)
    {
    #define offset(n) (char *) &t->r ## n - (char *) &t->r0
      static const reg_offsets[] = { offset(0), offset(1), offset(2),
                                     offset(3)};
    #undef offset
      return *(int *)((char *) &t->r0 + reg_offsets[regno]);
    }


This actually works, if I remove the dummy0
field of struct state. Otherwise, the compiler complains about non constant
initializers. I can take the static off the offsets array declaration,
but then I am left with the array being set up each time the function
is called which is not very efficient.

Gcc is justified in the sense that I don't think the standard requires
this to work. However, it is frustrating that it *almost* does what I
want.

So, under what circumstances is the difference between the addresses of
two parts of one object treated by gcc as a constant expression?

Is there a better way of doing what I want? The struct state is not
mutable. I'd prefer not to have a stack of hand calculated constants
around.


--
Ian Dall          I'm not into isms, but hedonism is the most
                  harmless I can think of. -- Phillip Adams

internet: dall@hfrd.dsto.gov.au
Technical Details
Message-ID: <488lt6$qg5@fang.dsto.defence.gov.au>
Path: arc1-ca.pugleaf.net!unknown!not-for-mail

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: 11318c,45bd1c7bd76217,start
X-Google-Attributes: gid11318c,public
From: dall@hfrd015.dsto.gov.au (Ian Dall)
Subject: Offsets in structures
Date: 1995/11/13
Message-ID: <488lt6$qg5@fang.dsto.defence.gov.au>
X-Deja-AN: 119515616
distribution: world
organization: Defence Science and Technology Organization.
reply-to: dall@hfrd.dsto.gov.au
newsgroups: gnu.gcc.help