0

All this time I have been declaring variables inside loops without blinking an eyelid, assuming that compilers will always do the necessary optimization and not reallocate the memory for a variable for each iteration of the loop. Imagine my surprise on reading the following from the "C Bible" (K&R), Section 4.8 Block Structure:

An automatic variable declared and initialized in a block is initialized each time the block is entered.


So is K&R outdated, or is it a wrong assumption the compilers will always do the necessary optimization to ensure that memory allocation for a variable declared in a loop is done only once?

Sandeep
  • 1,245
  • 1
  • 13
  • 33
  • 1
    This may help: https://stackoverflow.com/questions/26556449/are-variables-inside-a-loop-while-or-for-disposed-after-the-loop-has-completed Quick snippet: "If the block is executed 100 times, then X is created and "destroyed" 100 times, and has 100 disjoint lifetimes." – the_electro_bros Nov 26 '22 at 00:35

0 Answers0