What is the difference between local and global variables in C?
| Local variable | Global variable |
|---|---|
| Declared inside a function or block | Declared outside all functions |
| Can be used only in that block | Can be used in all functions |
| Default value is garbage | Default value is 0 |
| Removed when the function ends | Lives until the program ends |
Try to use local variables as much as possible. Global variables can be changed from anywhere, so bugs are hard to find. See Scope and Storage Classes.
Learn more about the similar topics:
| Tutorials |
|---|
| C Functions |
| C Function Arguments and Return Value |
| C Call by Value and Call by Reference |
| C Recursion |
| C Scope and Storage Classes |
| Exercises & Assignments |
|---|
| Write a C program to find the factorial of a number using recursion |
| Write a C program to swap two numbers using a function and pointers |