Declaration of variables in C++ best practices
Hi, I recently decided to read over the C++ tutorials @ learcpp.com and found in their examples that they are declaring and assigning values to variables as they are used. Years ago when I began coding it was common practice to declare all variables(and constants) with comments at the beginning of the script rather than in the middle of the script as they are needed.
Is there a good reason why this practice is not encouraged now? Or is it still best practice to declare up top?
Maybe they are just doing this for the purpose of the tutorial to make grasping basic concepts easier?
Declaring vars at the top of a function makes it easier to see at a glance how much stack memory will be used. But beyond that I don't see any advantage.
C, up through, C89, required variable declarations at the beginning of a block. C++ allowed them to be declared anywhere. This was popular enough that it was added to C99 (along with // comments). There are some cases (references and objects without default constructors) where declaring at the start of a block might not be practical.
Best practice? Shrug. Declaring variables anywhere was a conscious decision.