2013-01-15 64 views
1

我想用非常量步定義枚舉。我希望兩個枚舉變量之間的步驟如下所示:如何定義枚舉增量步驟?

enum test { 
    a1 = 1, 
    a2 = 1<<2, 
    a3 = 1<<3, 
    a4, // a4 deduced automatically as 1<<4 
    a5 // a5 deduced automatically as 1<<5 
} 

有沒有一種方法可以按照上面的示例中的說明來定義它?

+2

C是一個非常簡單的語言,我不認爲它有任何功能試圖推斷從例子。 – Barmar

回答

3

您必須手動執行此操作,或者可能使用宏指令進行操作。

1

如果沒有assignemt用於枚舉成員,

  • 然後零將被視爲第一枚舉成員。

  • 對於其他會員,只需在其上添加一個 即可使用上一個會員的價值。

在您的程序分配(=)中的更多內容未在枚舉定義中使用運算符。它應該如下所示。

#include <stdio.h> 
enum test 
{ 
    a1 = 1, 
    a2 = 1<<2, 
    a3 = 1<<3, 
    a4, // a4 deduced automatically as 1<<4 
    a5 // a5 deduced automatically as 1<<5 
}; 

void main() 
{ 
    printf("%d, %d", a4, a5); 
} 

輸出

9, 10 
2

呢?

#include <stdio.h> 

#define enum_(x, n) x##n=1<<n 

enum type { 
    enum_(a, 0), 
    enum_(a, 1), 
    enum_(a, 2), 
    enum_(a, 3), 
    enum_(a, 4), 
    enum_(a, 5) 
}; 

int main(void) 
{ 
    printf("%d %d %d %d %d %d\n", a0, a1, a2, a3, a4, a5); 
    return 0; 
}