访问union的内部变量

时间:2012-09-11 04:54:03

标签: c

我正在阅读Libevent2.0的源代码,我发现了一些我无法理解的代码。为什么我们可以在不访问“_ev”和“ev_signal”的情况下访问成员“ev_ncalls”? 我遵守了一些无法通过gcc的代码。这是代码:

struct event {
    union {
            /* used for io events */
            struct {
                    TAILQ_ENTRY(event) ev_io_next;
                    struct timeval ev_timeout;
            } ev_io;

            /* used by signal events */
            struct {
                    TAILQ_ENTRY(event) ev_signal_next;
                    short ev_ncalls;
                    /* Allows deletes in callback */
                    short *ev_pncalls;
            } ev_signal;
    } _ev;
};

struct event *ev;
int ncall = ev->ev_ncalls;

1 个答案:

答案 0 :(得分:4)

这是因为event-internal.h有类似的东西:

#define ev_ncalls   _ev.ev_signal.ev_ncalls
#define ev_pncalls  _ev.ev_signal.ev_pncalls

所以当你说ev->ev_ncalls时,编译器会看到ev->_ev.ev_signal.ev_ncalls