【发布时间】:2012-05-04 18:25:03
【问题描述】:
我有点困惑为什么这个 C 宏无法编译:
#define LUA_GET_FIELD(Lua, idx, name, type) (\
lua_getfield((Lua), (idx), (name)), \
typeof(lua_to##type) __result = lua_to##type((Lua), -1), \
lua_pop((Lua), 1), __result)
调用时出现错误:
src/event.lcpp.c:134:15: error: expected primary-expression before ‘typeof’
src/event.lcpp.c:134:15: error: expected ‘)’ before ‘typeof’
如果我将typeof(lua_to##type) 替换为int,也会发生同样的情况,所以我怀疑问题与逗号有关。这样的表达式中间不能声明变量吗?
我知道 gcc 有一个从块返回值的扩展,但我想避免编译器扩展。我也意识到这应该改为内联函数,但现在我很好奇为什么宏不起作用。
【问题讨论】:
-
表达式
typeof(lua_to##type)的计算结果为函数类型,而不是lua_to##type函数返回的类型。 -
“我想避免编译器扩展” -
typeof是一个编译器扩展,所以如果你愿意使用它,那么下一步可能不会太糟糕。
标签: c macros comma-operator