Home > Back-end >  Will int declare a new variable in for loop?
Will int declare a new variable in for loop?

Time:08-31

In each loop, will it be a totally new a or original a?

  for(int i=0;i<5;i  )
  {
      int a=i;
      printf("a=%d\n",a);
  }
}

The execution result:

a=0
a=1
a=2
a=3
a=4

CodePudding user response:

There are two things:

  1. The value of a will be removed after the closing braces of the loop, so yeah it will be a totally new variable

  2. But when it comes to talk about from the perspective of compiler, it is not so, the value might still be residing in some register (IT IS NOT FLUSHED OUT)

CodePudding user response:

The scope of a is only until the closing brace of the for-loop.

for(int i=0;i<5;i  )
  {
      int a=i;                    //a new variable a will be created, initialized with the value of i 
      printf("a=%d\n",a);
  }                               // lifetime of the variable a will end, forget everything

So in each run through the loop there will be a new variable a.

CodePudding user response:

for(int i=0;i<5;i  ) //for loop will have 5 iterations starting at i value 0 - 4
  {
      int a=i; //each iteration a "new" variable "a" is declared and initialized to the value of i
      printf("a=%d\n",a); //prints the value of "a" to the standard out
  }
}

Your variable "a" resides inside the scope of the for loop block. Each iteration, that block will execute; at the end of the iteration, the block (everything inside curly braces) is discarded (may still be accessible somewhere in memory) and the block is executed once more with the new iteration. This means that the variable "a" is discarded at the end of the iteration and declared and initialized at the beginning of the new iteration (as a "new" variable).

  •  Tags:  
  • c
  • Related