Hasty Briefsbeta

Bilingual

Sizeof is surprisingly difficult to parse in C

8 hours ago
  • The operand of sizeof can be a unary expression or a parenthesized type name, with expressions not requiring parentheses.
  • Parsing sizeof involves first checking for an opening parenthesis and attempting to parse a type name; if that fails, treat it as an expression.
  • Compound literals like sizeof(int){0} complicate parsing because they may include postfix operators after the closing brace.
  • One solution is to handle compound literals by checking for a '{' token after a type name and then parsing any following postfix operators.
  • Another approach is to write a function that parses either a unary expression or a parenthesized type name without backtracking, but careful with expressions like sizeof(int)+1 to avoid parsing as a cast.
  • These principles also apply to the new _Countof operator in C2y.

Related

Loading…