Syntax. The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
The initialization is an expression that initializes the loop — it's executed once at the beginning of the loop. The termination expression determines when to terminate the loop. When the expression evaluates to false , the loop terminates.
This happens because declaring variables inside a for loop wasn't valid C until C99(which is the standard of C published in 1999), you can either declare your counter outside the for as pointed out by others or use the -std=c99 flag to tell the compiler explicitly that you're using this standard and it should interpret ...
for (int i = 0; ...)
is a syntax that was introduced in C99. In order to use it you must enable C99 mode by passing -std=c99
(or some later standard) to GCC. The C89 version is:
int i;
for (i = 0; ...)
EDIT
Historically, the C language always forced programmers to declare all the variables at the begin of a block. So something like:
{
printf("%d", 42);
int c = 43; /* <--- compile time error */
must be rewritten as:
{
int c = 43;
printf("%d", 42);
a block is defined as:
block := '{' declarations statements '}'
C99, C++, C#, and Java allow declaration of variables anywhere in a block.
The real reason (guessing) is about allocating internal structures (like calculating stack size) ASAP while parsing the C source, without go for another compiler pass.
Before C99, you had to define the local variables at the start of a block. C99 imported the C++ feature that you can intermix local variable definitions with the instructions and you can define variables in the for
and while
control expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With