Home > Mobile >  Variable initialization in for loop
Variable initialization in for loop

Time:03-06

I had such a question:What is the difference between

int i;
for(i = 0; i < n; i  )

and

for(int i = 0; i < n; i  )

Does this influence memory and time?

CodePudding user response:

C 2018 6.2.1 2 says:

For each different entity that an identifier designates, the identifier is visible (i.e., can be used) only within a region of program text called its scope

6.2.1 4 says:

Every other identifier [paragraph 3 discussed labels] has scope determined by the placement of its declaration (in a declarator or type specifier)… If the declarator or type specifier that declares the identifier appears inside a block or within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the end of the associated block…

Which portions of C source code form blocks is stated individually in several places.

6.8.2 1:

A compound statement [source code inside { and }] is a block.

6.8.4 3:

A selection statement [if, if … else, and switch] is a block whose scope is a strict subset of the scope of its enclosing block. Each associated substatement is also a block whose scope is a strict subset of the scope of the selection statement.

6.8.5 5:

An iteration statement [while, do … while, and for] is a block whose scope is a strict subset of the scope of its enclosing block. The loop body is also a block whose scope is a strict subset of the scope of the iteration statement.

Thus for (int i = 0; i < n; i ) declares an i whose scope is limited to the for statement. This i cannot be used after the for statement.

In contrast, the int i; before the for statement declares an i that can be used throughout the block it is in, which is the { … } that it is enclosed in.

CodePudding user response:

Assuming you have written this code in the main function,

int i;
for(i = 0; i < n; i  )

In the case above, i is a local variable of the main function. If the value of i is updated in the loop it will remain updated even after the loop ends. i is not destroyed after the for loop. This is useful in some programs where you need the value of i after the loop for later use.

for(int i = 0; i < n; i  ) 

In the case above, i is a local variable of the for loop. i will be destroyed once the loop is over.

  •  Tags:  
  • c
  • Related