Declaring variables in the loop init

Is it always best practise to declare and Initialise inside the for loop if you can?

Yes see this item and the previous one ES.5
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es6-declare-names-in-for-statement-initializers-and-conditions-to-limit-scope

This is why this feature was added to for loops after all. Not sure if it was pre-standard or C++98 but you used to have to write

int x;
for (x = 0; ...; ...)

It was only later that you could initialise it within the for.

Thanks Dan :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms