Variables
A variable is the name of the memory location. It is used to store information. Its value can be altered and reused several times. It is a way to represent memory location through symbols so that it can be easily identified.
Variables are key building elements of the C programming language used to store and modify data in computer programs. A variable is a designated memory region that stores a specified data type value. Each variable has a unique identifier, its name, and a data type describing the type of data it may hold.
Here are some key points about variables:
- A variable must be given a unique name (identifier).
- The data type of a variable determines what kind of data it can hold.
- Variables can be assigned values at the time of declaration or later in the code.
Types of Variables
- Local Variables:
- Declared inside a function or block.
- Accessible only within the function or block where they are declared.
- Not initialized automatically; must be explicitly initialized.
- Global Variables:
- Declared outside all functions.
- Accessible throughout the program by all functions.
- Retain their value throughout the program's execution.
- Static Variables:
- Retain their value between multiple function calls.
- Can be local or global.
- Initialized only once, and their lifetime is throughout the program's execution.
- Automatic Variables:
- Declared using the auto keyword (though optional as auto is default).
- Limited to the scope of the block in which they are declared.
- External Variables:
- Declared using the extern keyword.
- Allows access to a global variable defined in another file.
- Register Variables:
- Declared using the register keyword.
- Suggests storing the variable in the CPU register for faster access (subject to availability).
Code Example: Declaring and Using Variables
#include <stdio.h>
int globalVar = 10; // Global variable
int main() {
int localVar = 5; // Local variable
static int staticVar; // Static variable (default value is 0)
printf("Global Variable: %d\n", globalVar);
printf("Local Variable: %d\n", localVar);
printf("Static Variable: %d\n", staticVar);
return 0;
}
Output
Global Variable: 10
Local Variable: 5
Static Variable: 0