2015年6月29日 星期一

[C筆記]struct union enum 實作

介紹

struct : 使用者變數不會只是簡單的 int or char 所以用結構來定義使用者所               需要的變數


enum:列舉 讓使用者只能輸入固定值(例如星期幾)(使用實不必加""字串符號)

union: 當使用者需要一個不是特定的單位時候就必須使用union
             範例中

               typedef union{
                          short count;
                          float weight;
                          float volume;
                           }quantity;

             使用者用到"量單位的變數" 可能是整數或者浮點數,就需要使用union ,原因是如果用 struct來做就會造成空間的浪費,必須浪費一個short (2byte)和2個  float (4byte)的記憶體空間來存一個值 ,union 則是以最大空間來變通  float (4byte) 可以省下許多記憶體空間。







sample code
#include <stdio.h>
#include <stdlib.h>
typedef enum{count,pounds,pints}unit; // 與struct不同  用,隔開
 typedef union{ // quantity x ={5};會被設定第一個欄位  //指定設定 quantity x ={.volume=1.5};                      short count;
        float weight;
        float volume;
        }quantity;
typedef struct {
        const char *name;
        const char *color;
        quantity amount;
        unit units;  
        }fruit;
   
void display(fruit x); //因為有fruit 所以必須放在 typedef struct fruit 下面   
int main(int argc, char *argv[])
{
  fruit apple = {"apples","red",.amount.count=150,count}; //不允許先宣告 下一行才設定值 !! apple ={}會被編譯器誤以為陣列 
  fruit strawberries = {"strawberries","pink",.amount.weight =1.5,pounds};
  fruit noisy ={"noisy","nocolor",.amount.volume =1.3,pints};
  display(apple);
  display(strawberries);
  display(noisy);
  return 0;
}
void display(fruit x)//如果是改值請用指標改記憶體內的值(這方法純輸出來看所以不帶入指標) 
{
     if(x.units == count)
        printf("%s is %s and %i\n",x.name,x.color,x.amount.count);
     else if(x.units == pounds )
         printf("%s is %s and %1.1f\n",x.name,x.color,x.amount.weight);
     else
         printf("%s is %s and %1.1f\n",x.name,x.color,x.amount.volume);
}

輸出結果


沒有留言:

張貼留言