📝

Global vs Local Variables in C++

Sep 8, 2025

Overview

The lecture explains the differences between global and local variables in C++, how their values are initialized, and the effect of using variables with the same name in different scopes.

Global and Local Variables

  • A global variable (e.g., int x;) is declared outside any function and accessible throughout the program.
  • A local variable (e.g., int y;) is declared inside a function and accessible only within that function.
  • Declaring int x; globally and int y; locally creates two separate variables.

Variable Initialization and Output

  • By default, global variables are initialized to zero if no value is explicitly assigned.
  • Local variables are not initialized by default and contain "garbage" values until assigned.
  • Printing uninitialized local variables may show unpredictable results.
  • Always assign a value to local variables before using them.

Assigning Values to Variables

  • Assign a specific value to a global variable (e.g., x = 20;) to control output.
  • Assign a specific value to a local variable (e.g., y = 10;) before using it in output.
  • After assigning, outputs will correctly display the set values.

Variable Name Shadowing

  • If a local variable shares the same name as a global variable (e.g., both named x), the local variable takes precedence within its scope.
  • When using cout for x inside the function, it will display the value of the local x, not the global one.

Key Terms & Definitions

  • Global Variable — A variable declared outside all functions, accessible from any part of the code, initialized to zero by default.
  • Local Variable — A variable declared inside a function, accessible only within that function, contains garbage value until explicitly assigned.
  • Garbage Value — Random or unpredictable value assigned to uninitialized local variables.
  • Variable Shadowing — When a local variable has the same name as a global variable, the local variable overrides the global one within its scope.

Action Items / Next Steps

  • Always initialize local variables before using them.
  • Try writing sample code to demonstrate variable scope and initialization effects.
  • Review the difference between local and global variables for upcoming assignments.