宏不是在運行時膨脹,他們使文本修改代碼它們到達編譯器之前。您可以使用連接運算符來獲得一個宏,你想要做什麼:
#define GET_NAME_INT(x) name ## x ## _int
GET_NAME_INT(0) /* this is name0_int */
GET_NAME_INT(1) /* this is name1_int */
但你不能遍歷這得到你想要的東西 - 使用I擴大在編譯時間namei_int變量。你不能將宏放在數組中,它們只是不是運行時存在的那些東西。你可以把函數指針放到數組中,我想這通常就是你想要的。即:(或者,如果你願意,宏)
struct my_args {int x, y, z};
void function1(struct my_args *);
void function2(struct my_args *);
void function3(struct my_args *);
void function4(struct my_args *);
...
int i;
void (*my_funcs)(struct my_args *)[] = {function1, function2, function3, function4};
struct my_args args= {0, 1, 50};
for(i = 0; i < 4; i++) {
my_funcs[i](&args);
}
如果你真的想用宏,可以消除由拉出成一個函數調用重寫「代碼」部分,即:
/* just an example, the do while is so you can put a ';' after and
* make it look like a statement */
#define DO_STUFF do{j += ((x + y - 4)/17 + i)}while(0)
i = 0;
if (name0_int == 0)
DO_STUFF;
i++;
if (name1_int == 0)
DO_STUFF;
i++;
if (name2_int == 0)
DO_STUFF;
像這樣調試宏代碼可能是一件很麻煩的事情,如果使用宏的目的是性能,那麼你可以考慮內聯函數,如果必須通過調試器進行爬網,可以關閉optomizations。
我認爲你正在尋找這個,http://stackoverflow.com/questions/1102542/how-to-define-an-enumerated-type-enum-in-c – user1399238
這些名稱是什麼' _int'宏擴展? – pat
我想你想要宏令牌串聯運算符:http://gcc.gnu.org/onlinedocs/cpp/Concatenation.html –