Quote:
Originally Posted by TimCraig
Good programming practices usually suggest that variables be given the smallest scope to do the job. This prevents accidental access via things like mispelling the variable name. It also limits name clashes for commonly used variable names and makes the logic easier to follow. That said, most programmers don't use block scope in C and the smallest common scope is the function. Using more descriptive names helps with name clashes but it's nice to be able to use a simple descriptive name without having to worry too much about it until the linker complains. Some coding styles preface global variables with "g_" and file scope statics with "s_" to help with clashes and to make it more obvious what the variable really is.
|
Very true. Keeping scope small also leads to much more readable code. For example, lets assume you are debugging a function that was written with no global variables. In this case you know that all function input MUST be passed through the arguments given to the function at the time the function was called. Once you verify the integrity of the paramaters passed the scope of your debugging is entirely within that function because it is impossible that any data besides the originally passed paramaters had made its way into that function.
On the other had if you have use of global variables then you have no conrtol over the data that the function is using. Vars could be changing mid-function making debugging work very hard.
Example: Your using variable x which is global. You call function process_x() passing it no args since x is global and you dont need to. At some point within function process_x you call another function process_y. Since its been a while since you wrote process_y you forgot that it tweaks the value of x. Because of this process_x starts screwing up and you spend WAY to long debugging it.