文章出處

聯合

  聯合和結構的區別是,結構會為每個字段申請一片內存空間,而聯合只是申請了一片內存空間然后所有字段都會保存到這片空間中,這片空間的大小由字段中最長的決定,下面我們就開始定義一個聯合

1 //聯合的定義
2 typedef union{
3     short count;
4     float weight;
5     float volume;
6 } quantity;

  聯合的使用 我們可以通過很多的方式為聯合賦值

 1 typedef struct{
 2     const char* color;
 3     quantity amount;
 4 }bike;
 5 
 6 int main(){
 7     //用聯合表示自行車的數量
 8      bike b={"red",5};
 9      printf("bike color:%s count:%i\n",b.color,b.amount.count);
10      //用聯合表示自行車的重量
11      bike b2={"red",.amount.weight=10.5};
12      printf("bike color:%s count:%f\n",b2.color,b2.amount.weight);
13     return 0;
14 }

  但是在讀取聯合的值的時候會很容易出問題,比如我們保存了一個float類型的字段,但通過short字段讀取,得到了與預期毫不相干的值

枚舉

  為了避免像聯合哪樣把字段的數據類型搞混亂,我們可以使用枚舉

 1 #include <stdio.h>
 2 
 3 //枚舉的定義和結構很類似
 4 typedef enum colors{RED,BLACK,BLUE,GREEN} colors;
 5 
 6 int main(){
 7     colors favorite=BLUE;
 8     printf("%i",favorite);
 9     return 0;
10 }

  如果想要保存多種數據類型l聯合畢枚舉更適用,那么要保存多條數據的話枚舉比聯合更適合


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()