Think of your C program like a big house.
The Living Room (Local Variables)
Imagine you are sitting in the living room. You have a toy car right in front of you. You can play with it, move it, and change its position. This is a local variable. It only exists while you are in that room. If you walk into the bedroom, you cannot reach the toy car in the living room. It is hidden from other parts of the house. When you leave the room, the toy might be put away or thrown away. It stops existing for that specific task.
| Scope | Visibility | Lifetime |
|---|---|---|
| Local | Only inside the function | Ends when function ends |
The Front Yard (Global Variables)
Now look outside the house. There is a big tree in the front yard. This is a global variable. Everyone in the house can see the tree. The kitchen, the bedroom, and the living room can all see it. It stays there as long as the house stands. It is shared by everyone.
Think of local variables like your personal backpack. Only you can open it. Global variables are like a community notice board. Everyone can read and write on it.
When you write code, use local variables for things that belong to one specific task or function. Use global variables for information that many parts of your program need to share, like the name of a game or a score that everyone needs to see.
Examples
- A community park is global because everyone can use it.
- You cannot reach the toy box from the kitchen.
Ask a question
See also
Loading…