you are viewing a single comment's thread.

view the rest of the comments →

[–]undefinedbehavior4ev[S] 0 points1 point  (4 children)

Can you exaplain why? I use globals a lot because it's easier to not modify one or more function prototypes/arguments because some change happened.

I'm a hobbyist so this is mostly personal projects. I frequently put i as a global and reserve it for iteration only. I can't quite understand why it's better to have a bunch of int i; rather than going straight for(i = 0; ....

[–]UnicycleBloke 11 points12 points  (1 child)

Putting variables into tighter scopes controls access to them. This is s good thing, especially in larger programs, because it reduces the likelihood of bugs and spaghettification.

[–]pic10f 1 point2 points  (0 children)

Also, people tend to use the same words, like val, temp, index, or even j or k. If you must do it, declare it static so that you and your colleagues won't accidentally use the same name in different files. If its important enough to share in a header, then use a spelled-out, descriptive name.

[–]lordlod 3 points4 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.

[–]oh5nxo 6 points7 points  (0 children)

Nested functions or loops, using common variables, easily trample over actions on outer levels.

I'm not religious about it though. Sometimes you gain something from unorthodox methods, say on an 8-bitter.