Fundamentals of Programming: Global and Local Variables - Wikibooks, open books for an open world (2024)

UNIT 1 - ⇑ Fundamentals of Programming ⇑

← Functions and ProceduresGlobal and Local VariablesThe Role of Variables →

Global variable - declared at the start of the program, their global scope means they can be used in any procedure or subroutine in the program

It is seldom advisable to use Global variables as they are liable to cause bugs, waste memory and can be hard to follow when tracing code. If you declare a global variable it will continue to use memory whilst a program is running even if you no longer need/use it.

Local variable - declared within subroutines or programming blocks, their local scope means they can only be used within the subroutine or program block they were declared in


Local variables are initiated within a limited scope, this means they are declared when a function or subroutine is called, and once the function ends, the memory taken up by the variable is released. This contrasts with global variables which do not release memory.

Take a look at this example:

Module GlocalsDim number1 as integer = 123Sub Main()console.writeline(number1)printLocalNumber()printGlobalNumber()End SubSub printLocalNumberDim number1 as integer = 234console.writeline(number1)End SubSub printGlobalNumberconsole.writeline(number1)End SubEnd Module

What would the output be?

Code Output

123
234
123


Why is this? Well we seem to have two versions of the variable number1.

  • The first version is declared on line 2, this isn't declared inside any sub routines so the variable has Global scope
  • The second version is declared inside the printLocalNumber sub routine. As it is declared inside a sub routine it is only able to be used inside this subroutine. And on line 12 when we use: console.writeline(number1) it prints out the local variable

So looking at the code inside the main sub routine we have 3 different ways of printing out the variable number1.

  1. Line 5. console.writeline(number1):This uses the global value of number1, as it is inside a sub routine with no other local declarations
  2. Line 6. printLocalNumber():This is calling on the subroutine printLocalNumber() which has a local variable number1 contained within it on line 11, therefore it uses the number1 value declared on line 11.
  3. Line 7. printGlobalNumber():This is calling on the subroutine printGlobalNumber() which has no local variable for number1, therefore it uses the global value for number1

Rules of thumb: If you want to quickly tell the difference between a global and a local variable use these quick rules. But be warned they might try to trick you!

  • If a variable is declared inside a function or a procedure it is a local variable
  • If a variable is declared inside a iterative or selective statement it is local
  • If the declaration is indented from the left hand boundary it probably meets one of the above criteria and is local
  • If it meets none of the above statements and is declared in the main body of code it is a global variable

Title

What is the difference between a global and a local variable?

Answer:

Global variables are accessible from all parts of a program, whilst local variables are only accessible within a programming construct such as a loop, function or procedure

Why is it a good idea to use local variables instead of global variable?

Answer:

Local variables release memory when you have finished with them, global variables are always stored in memory whether you need them or not

In what situation might you want to use a global variable?

Answer:

When you want to declare a variable that needs to be accessible by all parts of your code

List the global and local variables for the following. What will be the output for input 16:

Module calcAgeSub Main()dim age as integerconsole.writeline("age?")age = console.readline()printMonths(age)printDays(age)End SubDim months as integerSub printDays(a)Dim d as integerd = a * 365console.writeline(d)End SubSub printMonths(a)months = a * 12console.writeline(months)End SubEnd Module

Answer:

Locals: age, d

Globals: months

Code Output

age?
16
192
5840

For the above code how could you make the code more efficient, and why would it be more efficient?

Answer:

Make the months variable a local variable by putting it inside the printMonths(a) sub routine, if you leave it as a global variable it will be taking up memory even when you don't need it.

List the Global and Local variables in the following code, list the output:

Module greetingsDim q as integer = 6Sub sayGoodbye()for y = 1 to qconsole.write("bye,")loopEnd SubSub sayHello()dim q as integer = 4if q =< 4 thenconsole.write("hi,")elseconsole.write("hello,")endifEnd SubSub Main()console.writeline(q)sayHello()sayGoodbye()console.writeline(q)End SubEnd Module

Answer:

Locals: y (on line 4), q (on line 9)

Globals: q (on line 2)

Code Output

6
hi,bye,bye,bye,bye,bye,bye
6

Retrieved from ""

Fundamentals of Programming: Global and Local Variables - Wikibooks, open books for an open world (2024)

FAQs

Should you avoid global variables in JavaScript? ›

This is because once a global variable is declared, it can easily be modified by any successive function or block defined within the script, or multiple scripts, and any variable name can be misspelled by mistake, resulting in debugging issues especially for large codebases.

Is it bad to use global variables? ›

In this article, we talked about global variables. We should use them sparingly since they can introduce bugs and reduce our code's modularity.

How do you pass a global variable? ›

Use global variables until you are comfortable with passing arguments (variables) to other functions. The latter allows for modular programming where you can add a feature without disturbing a working program... simply make a function call to the new feature and "pass arguments" to the new feature, as in post #6.

How to avoid global variables in C? ›

Passing local variables as parameters to functions and using return values is another simple and great way to avoid global variables in C. By limiting their scope and passing them explicitly, we reduce the reliance on global states that can be altered anywhere and anyhow.

Why are global variables frowned upon? ›

Any component that depends upon a global variable cannot truly be closed to modifications – a change in one component that causes the variable to be used in an unexpected way will break other components using the variable.

What are the disadvantages of global variables in JavaScript? ›

Manipulating global variables within functions in JavaScript can have several drawbacks, including loss of encapsulation, potential naming conflicts, reduced code readability, and hindered code organization.

How do you destroy a global variable? ›

To delete a global variable from the global variable list, move the cursor to the line that contains the variable name and press the Delete function key.

Can you change a global variable? ›

You can access the global variables from anywhere in the program. However, you can only access the local variables from the function. Additionally, if you need to change a global variable from a function, you need to declare that the variable is global. You can do this using the "global" keyword.

What command creates a global variable? ›

To add a global variable, use one of the following options:
  1. On the QMF command line, enter the SET GLOBAL command with the following syntax: SET GLOBAL ( variable_name = value. ...
  2. On the QMF command line, enter the SHOW GLOBALS command to display the GLOBALS panel.

What is a good practice for global variables? ›

Global variables are considered when you want to use them in every function including main. Also remember that if you initialize a variable globally, its initial value will be same in every function, however you can reinitialize it inside a function to use a different value for that variable in that function.

Why do global variables make a program difficult to debug? ›

When a bug is related to a global variable, it can be difficult to identify where the error is occurring because the variable can be modified in many different parts of the program. This can lead to increased time spent on debugging and potentially more bugs in the program.

How do you reduce global variables? ›

Minimizing the use of global variables by using local variables interacts with stack usage control. For example, stack size can determine the number of local and global variables that the code generator can allocate in the generated code. For more information, see Customize Stack Space Allocation.

What is the alternative to global variables in JavaScript? ›

Use Local Variables Instead

The idea is that the global variable gState is replaced by the local variable sState in the script of your main application stack.

Can you have global variables in JavaScript? ›

The global object in JavaScript is available to all parts of your code. Any variables or functions inside the global object are in the global scope, which means you can use them in the functions, nested callbacks, and modules in your code — wherever they are.

Why should you avoid using global variables in programs that define functions? ›

Global variables can be altered by any part of the code, making it difficult to remember or reason about every possible use. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.

Why is it in general a good idea to leave the global scope of a website as is and never touch it? ›

There are many reasons to avoid touching the global scope: Naming conflicts: The global scope is shared across all scripts on a web page. If you introduce new global variables or modify existing ones, you risk causing naming conflicts with other scripts or libraries used on the same page.

Top Articles
Why was my transfer (or withdrawal) to my external bank account rejected or canceled?
Create a form - Microsoft Support
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
How To Cut Eelgrass Grounded
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Dmv In Anoka
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Umn Biology
Obituaries, 2001 | El Paso County, TXGenWeb
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Colin Donnell Lpsg
Teenbeautyfitness
Weekly Math Review Q4 3
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
San Pedro Sula To Miami Google Flights
Selly Medaline
Latest Posts
Article information

Author: Prof. Nancy Dach

Last Updated:

Views: 5658

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Prof. Nancy Dach

Birthday: 1993-08-23

Address: 569 Waelchi Ports, South Blainebury, LA 11589

Phone: +9958996486049

Job: Sales Manager

Hobby: Web surfing, Scuba diving, Mountaineering, Writing, Sailing, Dance, Blacksmithing

Introduction: My name is Prof. Nancy Dach, I am a lively, joyous, courageous, lovely, tender, charming, open person who loves writing and wants to share my knowledge and understanding with you.