Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Anonymous Union และ Structure ใน C

Anonymous Union/Structure คือ Union/Structure ที่ไม่มีชื่อ ใช้เป็น Nested Member เข้าถึง Member โดยตรงไม่ต้องผ่านชื่อ

ตัวอย่าง

#include <stdio.h>

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

int main() {
    struct point pt;
    pt.x = 10;  // เข้าถึงโดยตรง ไม่ต้อง pt.anon.x
    pt.y = 20;
    printf("Point (%d,%d)", pt.x, pt.y);
    return 0;
}

ผลลัพธ์

Point (10,20)