错误:'if'之前的预期表达式

时间:2015-11-13 15:15:35

标签: c macros syntax-error

这是我的代码,我不知道我错在哪里,什么是"表达"?

#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

2 个答案:

答案 0 :(得分:6)

(if(expression) {} else {})是无效的语法。

尝试

#define m(smth) if(sizeof(smth) == sizeof(int)) {printf("%d", (int) smth);} else{puts((char*)smth);}

答案 1 :(得分:3)

你不能将C中的块括在大括号中(()) - 只需删除它们,你应该没问题。此外,使用大括号括起smth的呼叫可能不是一个坏主意:

#define m(smth) if(sizeof(smth) == sizeof(int)) {printf("%d", (int) (smth));} else{puts((char*)(smth));}