What is a Variable?
A variable is a name given to a memory location to store values in a computer program. It is used to store information that can be referenced and manipulated in a program.
We can choose any name for the variable, but it must follow the programming semantics[TBD]. Such as it can be, a, b, x, y, z, sub, div, total, avg, etc.
EXAMPLE
Let's say there are two values, 10 and 20, that we want to store and use in our program. For this, we need to use a variable, and we will do the below steps:
- First, we will create or declare a variable with a suitable name.
- Assign those values to the variables to store them.
- Once these values are stores, we can use these variables with their name in our program.
As we can see in the above image, there are two memory slots, 001 and 002, and we have given names to these locations as A and B. A is containing 10, and B is containing 20.
Different programming languages have different ways to declare the variable. For example, in C language, we can declare the variable in the following manner:
Syntax: (Variable declaration syntax in C language)
datatype v1, v2, v3,....;
*Example:
*
#include
void main(){
int a;
int b;
int sum;
}
Types of variable
- Global Variable: Outside of all the functions
- Local Variable: Within a function block:
What is a Global Variable?
- Global variables are those variables which are declared outside of all the functions or block and can be accessed globally in a program.
- It can be accessed by any function present in the program.
- Once we declare a global variable, its value can be varied as used with different functions.
- The lifetime of the global variable exists till the program executes. These variables are stored in fixed memory locations given by the compiler and do not automatically clean up.
- Global variables are mostly used in programming and useful for cases where all the functions need to access the same data.
Example
#include
int a=50, b=40;
void main()
{
printf("a = %d and b=%d",a,b);
}
*What is a Local Variable?
*
- Variables that are declared within or inside a function block are known as Local variables.
- These variables can only be accessed within the function in which they are declared.
- The lifetime of the local variable is within its function only, which means the variable exists till the function executes. Once function execution is completed, local variables are destroyed and no longer exist outside the function.
- The reason for the limited scope of local variables is that local variables are stored in the stack, which is dynamic in nature and automatically cleans up the data stored within it.
- But by making the variable static with "static" keyword, we can retain the value of local variable.
Example
#include
void main()
{
int x=50, y=40;
printf("x = %d and y=%d",x, y);
}