C: Creating and returning a variable in a macro
-
03-06-2021 - |
Question
I'm a bit confused as to why this C macro fails to compile:
#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)
When invoking it, I get errors:
src/event.lcpp.c:134:15: error: expected primary-expression before ‘typeof’
src/event.lcpp.c:134:15: error: expected ‘)’ before ‘typeof’
The same happens if I replace typeof(lua_to##type)
with just int
, so I suspect the issue is to do with the commas. Can you not declare variables in the middle of an expression like this?
I know gcc has an extension for returning values from blocks, but I want to avoid compiler extensions. I also realize this should be changed to an inline function, but now I'm curious why the macro doesn't work.
Solution
Standard C indeed does not allow you to arbitrarily define new variables inside expressions. Older standards didn't even allow them anywhere but at the start of a block (that is, you couldn't intermix them with statements either).