sysprog21 / shecc

A self-hosting and educational C optimizing compiler
BSD 2-Clause "Simplified" License
1.11k stars 118 forks source link

Declare variables where needed #115

Closed jserv closed 6 months ago

jserv commented 7 months ago

In C99, it is possible to declare variables precisely where they are needed, a feature also present in C++. Variables can also be declared within the control structure of a for loop, a feature introduced in C99:

 for (int x = 0; x < 10; x++) {  /* This is permitted starting with C99 */
    ...
}

The C99 standard says: (6.8.5.3 The for statement)

for ( clause-1 ; expression-2 ; expression-3 ) statement behaves as follows: The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body. The expression expression-3 is evaluated as a void expression after each execution of the loop body. If clause-1 is a declaration, the scope of any variables it declares is the remainder of the declaration and the entire loop, including the other two expressions; it is reached in the order of execution before the first evaluation of the controlling expression. If clause-1 is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.

This enhancement simplifies the code by allowing variable declarations closer to where they are used, thereby improving readability and maintainability. shecc should support this feature.