Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Anonymous Union và Structure trong C

Ở đây ta xem Anonymous Union và Structure trong C. Là union/structure không tên. Vì không tên, không tạo đối tượng trực tiếp. Dùng như nested struct/union.

Ví dụ anonymous union/structure:

struct {
    datatype variable;
    ...
};
union {
    datatype variable;
    ...
};

Ví dụ struct point chứa anonymous struct holding x, y. Truy cập thành viên anonymous trực tiếp.

Ví dụ

#include <stdio.h>

struct point {
    // Anonymous structure
    struct {
        int x;
        int y;
    };
};

int main() {
    struct point pt;
    pt.x = 10;
    pt.y = 20;
    printf("Point (%d,%d)", pt.x, pt.y);
    return 0;
}

Kết quả

Point (10,20)