問題描述
錯誤:“if”之前的預期表達式 (error: expected expression before ‘if’)
這是我的代碼,不知道哪裡錯了,什麼是“表達式”?
#define m(smth) (if(sizeof(smth) == sizeof(int)) {printf("%d", (int) smth);} else{puts((char*)smth);})
int main(void) {
m("smth");
}
這裡是輸出:
/home/roroco/Dropbox/rbs/ro_sites/c/ex/ex2.c: In function ‘main’:
/home/roroco/Dropbox/rbs/ro_sites/c/ex/ex2.c:18:18: error: expected expression before ‘if’
#define m(smth) (if(sizeof(smth) == sizeof(int)) {printf("%d", (int) smth);} else{puts((char*)smth);})
^
/home/roroco/Dropbox/rbs/ro_sites/c/ex/ex2.c:21:5: note: in expansion of macro ‘m’
m("smth");
^
make[3]: *** [ex/CMakeFiles/ex2.dir/ex2.c.o] Error 1
make[2]: *** [ex/CMakeFiles/ex2.dir/all] Error 2
make[1]: *** [ex/CMakeFiles/ex2.dir/rule] Error 2
make: *** [ex2] Error 2
參考解法
方法 1:
(if(expression) {} else {})
is not valid syntax.
Try
#define m(smth) if(sizeof(smth) == sizeof(int)) {printf("%d", (int) smth);} else{puts((char*)smth);}
方法 2:
You can't enclose a block in C in braces (()
) ‑ just remove them, and you should be OK. Also, it probably won't be a bad idea to surround calls to smth
with braces:
#define m(smth) if(sizeof(smth) == sizeof(int)) {printf("%d", (int) (smth));} else{puts((char*)(smth));}
(by nwaicaethi、Almo、Mureinik)