4

This question already has an answer here:

Im a beginner using visual studio 2013, and I know what they are, but I'm puzzled, why would one use a local variable? I would always just use a global variable.

marked as duplicate by Philipp, Ixrec, gnat, Doc Brown, David Arno May 16 '16 at 13:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    vs20*13*? upgrade immediately – Ewan May 14 '16 at 10:28
  • 3
    And then someone else uses the same global variable without noticing, and suddenly you have a bug that takes you ages to find. – gnasher729 May 14 '16 at 19:00
  • 1
    @gnasher729: I would not restrict what you wrote to the case where "someone else" uses the variable. – Doc Brown May 14 '16 at 22:24
14

This is a great question! Much programming advice and "best practices" comes down to the question of managing complexity. Or to put it plainly: How do we write and manage a large complex program without being overwhelmed. The solution is (like with most large problems) to split it into smaller, more manageable pieces.

Each variable is a bit of complexity, but a global variable adds complexity to the whole program (because it may have effects all over the program, hence the name), while a local variable adds complexity only in a single isolated unit, the function.

The worst fear of a developer is to have a program where a change in a single function causes a totally different part of the program to fail. Each global variable increases this risk.

3

A global variable allows different components to communicate by reading from and writing to a common memory location. In this way, different components are dependent on each other / coupled: each component has expectations about the values contained in the global variable, and all other components must fulfill these expectations if you want your program to work properly.

Coupling increases the complexity of your software: when modifying one piece of code, you have to keep in mind all possible repercussions of the change on other components that depend on it.

So, by using a local variable you decrease the dependencies between your components, i.e. you decrease the complexity of your code. You should only use global variable when you really need to share data, but each variable should always be visible in the smallest scope possible.

1

Trying to think of an example where local variables are nescessary rathet than just good practice.

Consider a shopping basket with items and tax.

Global double CostOfShopping 

AddItem(item)
{
    CostOfShopping += item.price
}

AddTax()
{
    CostOfShopping =* TaxRate
}

So the order in which we add items and calc tax can change the cost of shopping. Esp. If we add two items!

Vs

double GetCostOfShopping(items)
{
    var tot = 0;
    Foreach(item)
        tot+=item.price;
    tot = tot * taxRate;
    return tot;
}

Because you total up with a local variable you control the order of the calculation within the function and prevent any adding of items after the tax calc

1

In addition to the other fine answers, we should consider the separate yet closely related notions of variable lifetime, variable scope, and access permission; let's consider them relative to concept of global, static, and local variables. Teasing these apart will allow us to analyze some of the differences in declarations.

And the point that @JacquesB makes about program complexity is spot on.

Each of the above can be used to reduce or magnify program complexity.

Lifetime is the effective duration of the variable; simply, how long the variable lives. A global variable lives for the length of the whole program. A local variable lives for the length of the method it is in (modulo minor differences in programming languages, and the notion of scope). A variable that lives longer has more potential effect on program complexity. Static variables have the same lifetime as global variables.

Let's also note that when there are multiple variables of whole program lifetime (global or static), there are initialization ordering issues (that are or are not resolved by initialization ordering of the language). Termination ordering issues are also present.

Scope is a notion of the context and environment of sharing. Most languages allow nesting of scopes. A global variable is in the largest scope, meaning it is being shared to all other code. A static variable is (potentially) narrowed in scope to the class that is defining it, so it's sharing can be limited to the one class rather than to all functions (also modulo differences in programming languages, and the notion of access permission). A local variable is declared one of the smallest scopes possible, which is function scope, and as such is only accessible to code within the function. Some languages allow inner scopes to further restrict the sharing of the variable to even less code.

Usually variables declared in a function or a nested scope also have function or nested scope lifetime, but this isn't always the case because of language differences and features such as closures, which can effectively extend the lifetime of local variables.

Access permission grants read and/or write permission to various audiences. When we speak of global variables, the access permission connotated is generally both read and write, the most permissive permission. Languages that support static variables on the other hand, generally allow custom access restrictions to be applied, such as public or private. Public being the same as global read/write, and private restricting access to the scope (i.e. the defining class).

Local variables, by definition in most languages are inaccessible to other code in other functions, though languages generally do not attempt to restrict read vs. write for locals (though some languages like Swift and Javascript (and others) support write-once (initialize only) via a LET or const keyword, not to be confused with VB's LET keyword for value assignment vs. the SET for reference assignment).

Reasoning over most of what's happening regarding state in function scope does not require whole program analysis (modulo language differences, and parameter passing methods).

In summary

Global variables live for the lifetime of the program, are shared to all functions, and generally allow read & write access.

Static variables live for the lifetime of the program; allow for restricted scope (to the class) and potentially allow different read vs. write permission.

Local variables on the other hand, live for the lifetime of the (function or other) scope, are shared only to code in the same scope.

Decomposing these aspects of variable declaration, you can probably imagine the effect each of these has on potential complexity, and the effort required by humans or tools with regard to analysis of what the program is doing or has the potential to do.

  • Excellent answer, just a small comment. OP is using VS2013, which means he's using VB.Net. The Let and Set keywords were retired with VB6 and are not part of the VB.Net language. – RubberDuck May 15 '16 at 2:08
  • @RubberDuck, good info, thx! Didn't know those keywords were retired. – Erik Eidt May 15 '16 at 4:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.