mercredi 26 mai 2021

Declaring variable inside the cycle - good style in modern C++? [duplicate]

Is there any reason in modern C++ to write like this:

for (int i =0, temp =0; i<size; i++)
{
   //some code
   temp = vec[i]*3;
   //some code;
}

From readability perspective would it be better to write like this?

for (int i =0; i<size; i++)
{
   //some code
   auto temp = vec[i]*3;
   //some code;
}

Anyway modern compiler would reserve memory on the stack for temp at the beginning of the function and won't create it in every cycle loop. Correct? Or tehre are still some situation when the first option is preferable?

PS: don't comment pls on exactly this code, it's obviously oversimplifying, but I think I've shown here the idea of the question.

Aucun commentaire:

Enregistrer un commentaire