Is it advisable to declare and initialize a variable within a loop?

4

good. after solving this I exercise with this Answer I skip the doubt if it is a good idea to declare and initialize a variable within a loop. this is done in order to avoid writing i = 0 and of = "email_.txt" in the code.

note: my doubt is addressed with a more technical than visual approach.

    
asked by bassily 01.10.2016 в 02:02
source

2 answers

7

The ideal is to reduce the scope of the variables to the maximum, so that their life is as short as possible. This, although it does not seem like it, improves the security of the code.

It is very important not to reuse a variable for different uses as it helps create confusion.

These two points have the conclusion that we must avoid static variables except very justified cases.

The variable we use to loop through a loop should normally be declared in the loop itself. Thus at the end of the loop the variable will disappear:

for(int i=0; i<10; ++i)
  std::cout << i;
std::cout <<i; // Error. i no existe en este punto.

If a function has two or more loops, it is normal to repeat the previous operation for each loop.

    
answered by 01.10.2016 / 08:50
source
1

If you can do it as long as the scope of that variable is inside the loop ... there's nothing wrong with that ...

    
answered by 01.10.2016 в 06:14