What are the differences between Local and Global Variable?

Local Variable:

  • Scope: Local variables are declared within a specific block, function, or scope.
  • Lifetime: They exist only within the block or function in which they are declared.
  • Access: Accessible only within the block or function where they are defined.
  • Initialization: This may not be initialized by default and must be explicitly assigned a value before use.
  • Memory Allocation: Typically allocated on the stack.
  • Visibility: Not visible or accessible outside the block or function where they are declared.

Global Variable:

  • Scope: Global variables are declared outside of any function or block, making them accessible throughout the entire program.
  • Lifetime: They exist for the entire duration of the program's execution.
  • Access: Accessible from any part of the program, including functions and blocks.
  • Initialization: May be initialized or uninitialized, and they retain their values between function calls.
  • Memory Allocation: Typically allocated in the data segment of the program.
  • Visibility: Visible and accessible from any part of the program.