Originally Posted by Zssfssz
In all the C, C++, and Obj-C tutorials I have read they say all vareabls need to be declared at the top of a function (or be global) or there will be problems.
For C++, that would be a major flaw in the tutorial.
For ANSI C, it is roughly correct.
Best practice is declaring variables with the narrowest scope. The compiler's optimizer often fails to deduce a narrow scope (though it tries) and much better asm code can be generated when the optimizer knows about narrow scope. But the more important reason is to help the maintenance programmer. When you want to correct or enhance a module, obvious narrow scopes for most of the variables make understanding the code much easier.
In C++, it is also best practice, when possible, to delay declaring each variable until the initial value for that variable is available. There are many situations in which having a default constructor for a type is a problem. Without a default constructor, you need some initial value to declare the variable. It is confusing and inefficient to declare a dummy initial value that isn't used. Even with a default constructor (or POD objects not needing construction) the declaration without the initial value can be confusing to both the maintenance programmer and the optimizer.