- ยูเนี่ยนจะจองพื้นที่มากที่สุดเท่ากันชนิดข้อมูลที่มากที่สุดของสมาชิก
- ยูเนี่ยนจะทำการเก็บค่าได้ครั้งละ 1 สมาชิก
- การประกาศยูเนี่ยนจะคล้าย structure แต่ใช้คียร์เวิร์ด union แทน structure
- การใช้ typedef จะช่วยให้โค๊ดอ่านง่ายขึ้น มีความหมายมากขึ้น
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#define PRICE 'P' | |
#define QNTY 'Q' | |
#define SERIES 'S' | |
typedef struct phone { | |
char option; | |
union detail_ { | |
int qnty; | |
float price; | |
char series; | |
} detail; | |
} Phone; | |
void showDetails(Phone phone); | |
int main(void) { | |
Phone iPhone; | |
iPhone.option = PRICE; | |
iPhone.detail.price = 566.6; | |
showDetails(iPhone); | |
iPhone.option = QNTY; | |
iPhone.detail.qnty = 6; | |
showDetails(iPhone); | |
iPhone.option = SERIES; | |
iPhone.detail.series = 's'; | |
showDetails(iPhone); | |
return 0; | |
} | |
void showDetails(Phone phone) { | |
if (phone.option == PRICE) { | |
printf("%f",phone.detail.price); | |
} else if (phone.option == QNTY) { | |
printf("%d",phone.detail.qnty); | |
} else if (phone.option == SERIES) { | |
printf("%c",phone.detail.series); | |
} | |
printf("\n"); | |
} |