C語言 枚舉實驗

C語言 枚舉實驗
【摘要】有關c語言枚舉類型的相關實驗。
 
【目的】實驗驗證是否在預處理時進行替換。
// test.c預處理測試
enum Etype
{
    A,    // 未賦值的枚舉值
    B=2 // 賦值的枚舉值
};
#define C 3 // 宏定義
 
void main()
{
int a = A;
int b = B;
int c = C;
}
筆者在Code Warrior下預處理,可以使用預處理指令來預編譯這段代碼——$ gcc -E test.c
預處理結果:
/*        2 */  enum Etype
/*        3 */  {
/*        4 */  A ,
/*        5 */  B = 2
/*        6 */  } ;
/*        9 */  void main ( )
/*       10 */  {
/*       11 */  int a= A ;
/*       12 */  int b= B ;
/*       13 */  int c= 3 ;
/*       14 */  }
 
可以看出,#define 定義的常量,在預處理的時候做了替換,而enum定義的常量,並沒有進行替換。
補充一下,預處理只進行刪除註釋(//、/**/)、連接符(\)、預處理命令執行(#,##,#@)。
 
 
【目的】通過sizeof看枚舉定義的變量所佔的空間

#include <iostream>
 
using namespace std;
 
enum unsigned_char_e :  unsigned char
{
}a;
enum  signed_char_e :   signed char
{
}b;
enum  default_e
{
}c;
 
int main()
{
    cout << sizeof(unsigned_char_e)<< "\t" << sizeof(unsignedchar) << "\t" <<sizeof(a) << "\n" ;
    cout << sizeof(signed_char_e)<< "\t" << sizeof(signedchar) << "\t" <<sizeof(b) << "\n" ;
    cout << sizeof(default_e)<< "\t" << sizeof(int)<< "\t" << sizeof(c) << "\n" << endl;
    return 0;
}
編譯成功,兩個警告
enum unsigned_char_e :  unsigned char
enum  signed_char_e :   signed char
範圍枚舉僅僅在C++0x標準或gnu++ox標準中使用
warning: scoped enums only available with -std=c++0x or -std=gnu++0x|
 
1       1       1
1       1       1
4       4       4
 
 
Process returned 0 (0x0)   execution time : 0.433 s
Press any key to continue.
 
 
這種對枚舉聲明的變量限定空間大小的寫法只在新標準C++中可用。
在C中編譯不通過。
發佈了27 篇原創文章 · 獲贊 24 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章