sebsite

sizeof is surprisingly difficult to parse in c

(because of course it is, literally everything in c is surprisingly difficult to parse).

for those unaware, the operand of sizeof is either a unary expression, or a parenthesized type name. so the following are all valid:

sizeof 67
sizeof(67)
sizeof(int)
sizeof (x).y

note that only types need to be parenthesized; expressions don't.

the naive way to parse this is to first check for an opening parenthesis, and if one is found, try to parse a type name. luckily, that only requires reading one additional token. if that fails, push the parenthesis back into the token stream, and parse an expression instead.

there's a problem with that approach though: compound literals exist:

sizeof(int){0}

(int){0} is an expression. this is valid C code! but it makes parsing much more difficult. you could just add a special case when parsing a type name, to check for a { token after the closing parenthesis, and if one is found, parse a compound literal instead. but that isn't enough either, because the expression can be followed by any number of postfix operators:

sizeof(T){}.x[0]()

so one approach is to expand that special case to parse any number of postfix operators after the compound literal. another approach is to write a function which tries to parse either a unary expression or a parenthesized type name, so no backtracking is required. but you have to be careful with this approach. it's tempting to combine parsing unary expressions and cast expressions into a single function, to save on backtracking. normally you can do that without any problems, but that doesn't work here:

sizeof(int)+1

that's an addition expression, not the size of a cast expression.

(everything here also applies to c2y's newly introduced _Countof)