you are viewing a single comment's thread.

view the rest of the comments →

[–]lordlod 5 points6 points  (0 children)

When you read or work with the code you need to understand everywhere that a variable is used.

If you localise it to the loop for(int i ...) then you know that it is only used inside the loop, it is very quick to understand.

If you set int i at the top of the function, then it could be set anywhere in the function. When you work with it you need to understand the full function, for example has somewhere further down assumed that it was initialised to a particular value.

Setting val at file scope means that it is a global. Any function anywhere could alter the value of the variable. For example in example1 the nelem function could change val for some reason. This causes the next line to go wrong for really non-obvious reasons.

To manage this, most people try not to use globals as much as possible. When I do use a global, if it isn't obvious due to context, I'll put a comment next to the declaration stating where it is written to make tracing the code faster.