Structures and casting in C

前端 未结 8 1485
野性不改
野性不改 2020-12-16 02:07

I was wondering:

If I have structure definitions, for example, like this:

struct Base {
  int foo;
};

struct Derived {
  int foo; // int foo is comm         


        
相关标签:
8条回答
  • 2020-12-16 02:56

    The great/bad thing about C is that you can cast just about anything -- the problem is, it might not work. :) However, in your case, it will*, since you have two structs whose first members are both of the same type; see this program for an example. Now, if struct derived had a different type as its first element -- for example, char *bar -- then no, you'd get weird behavior.

    * I should qualitfy that with "almost always", I suppose; there're a lot of different C compilers out there, so some may have different behavior. However, I know it'll work in GCC.

    0 讨论(0)
  • 2020-12-16 03:02

    There is another little thing that might be helpful or related to what you are doing ..

    #define SHARED_DATA int id;
    
    typedef union base_t {
        SHARED_DATA;
        window_t win;
        list_t   list;
        button_t button;         
    }
    
    typedef struct window_t {
        SHARED_DATA;
        int something;
        void* blah;
    }
    
    typedef struct window_t {
        SHARED_DATA;
        int size;
     }
    
    typedef struct button_t {
        SHARED_DATA;
        int clicked;
     }
    

    Now you can put the shared properties into SHARED_DATA and handle the different types via the "superclass" packed into the union.. You could use SHARED_DATA to store just a 'class identifier' or store a pointer.. Either way it turned out handy for generic handling of event types for me at some point. Hope i'm not going too much off-topic with this

    0 讨论(0)
提交回复
热议问题