Vishwas M P
Vishwas M P

Reputation: 41

sizeof operator evaluates in which stage of compilation in gcc

sizeof is a compile time operator. See here.

Compilation has many stages. At which stage is the sizeof operator evaluated?

Upvotes: 2

Views: 387

Answers (1)

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43558

Typically, after the preprocessor runs and produces the preprocessed translation unit (whole header files pasted in the place of #include, #define's substituted all over the place, inactive branches of #ifdef conditionals completely removed, etc.), the compiler runs. Most modern compilers are usually also able to do the preprocessing themselves, but for historic reasons, the C preprocessor (cpp) and the C compiler (cc) are at least conceptually distinct. The output of the former serves as input to the latter.

At consequent stages, it is entirely up to the internal implementation of the compiler what these stages are and what their order is. The most "traditional" pipeline, however, is:

  • Lexing: separation of tokens from one another;
  • Parsing: interpreting the combinations of tokens according to the language grammar and producing a parse tree;
  • Producing an Abstract Syntax Tree: the parse tree is taken as input and a more usable, better annotated tree is produced;
  • Scope analysis: matching the used identifiers with their respective declarations, emitting errors in case of undeclared identifiers;
  • Type checking: checking whether the type of each expression matches the expected type in the particular context. After this stage has passed and no errors have been emitted, the program is considered syntactically and semantically correct, so we can proceed with the next step;
  • Code generation and optimisation: possibly at this stage, the compiler would emit, for example, 4 in place of the abstract node that represents sizeof(int). It would also chew up constant expressions like 3 + 4 into 7.

Note that sizeof can be evaluated at runtime in case it is applied to a variable-length array (C99 onwards):

int n;
n = ...;
int vl_arr[n];
sizeof(vl_arr); // could be evaluated at runtime if "n" is not known at compile-time

Upvotes: 3

Related Questions