2012-04-02 75 views
2

隨着使用普通Ç預處理宏,是有可能創造這樣的:自動增加宏擴展

INIT_BASE(0x100)      // init starting number 

#define BASE_A GET_NEXT_BASE   // equivalent to #define BASE_A 0x101 
#define BASE_B GET_NEXT_BASE   // 0x102 
#define BASE_C GET_NEXT_BASE   // 0x103 
+6

爲什麼它需要一個預處理命令#define?爲什麼不只是一個枚舉? – 2012-04-02 15:44:39

回答

3

宏不能自動執行該類型的計數,但enum s可以。

#define INIT_BASE 0x100 
enum foo 
{ 
    BASE_A = INIT_BASE + 1, 
    BASE_B, 
    BASE_C, 
    ... 
}; 

除非你真的使用宏,你將不得不做手工計數:

#define INIT_BASE 0x100 
#define BASE_A (INIT_BASE + 1) // equivalent to #define BASE_A 0x101 
#define BASE_B (INIT_BASE + 2) // 0x102 
#define BASE_C (INIT_BASE + 3) // 0x103 
+0

...並且你想在'INIT_BASE + N'表達式周圍放置圓括號。 – 2012-04-02 15:55:37

+0

美麗!我錯誤地認爲枚舉在運行時佔用內存。 – Saideira 2012-04-02 17:00:06

3

你試過:

#define BASE_A (INIT_BASE+1) // equivalent to #define BASE_A 0x101 
#define BASE_B (BASE_A+1)   // 0x102 
#define BASE_C (BASE_B+1)   // 0x103