A variable is a name of a location in a memory where values are stored. The value stored in the variable can be changed and can be reused as many times as possible depending on the instructions provided by the user.
Syntax to define a variable:
type variable_name;
Where “type” represents the datatype of the variable and the “variable name” is the name of the variable which you want to give.
Example:
int age;
char b;
double c;
Here are some examples of variables in C. In the above example age, b and c are the name of the variable whereas int, char and double are the datatypes.
Rules for Defining Variables:
There are certain rules you need to follow to define a variable in C, the rules are:
- A variable can have an alphabet as well as a digit.
- A variable can start with an alphabet or underscore.
- A variable cannot start with a digit.
- A variable should not have space within its name.
- A variable should not be a reserved word that means keywords, eg: long, for, while etc.
Some Examples Of Valid Variable Name:
int x;
char _bd;
double c33;
Types Of Variable In C:
In C language there are different types of variable present such as:
- local variable
- global variable
- automatic variable
- static variable
- external variable
Local Variable:
A variable declared in a function or block is called a local variable. It should be declared at the beginning of the block and should be initialized before use.
Examples:
#include<stdio.h>
int main(){
int a=20;//local variable, local to the block
}
Contributed By: Soham Malakar
Global Variable:
A variable declared outside a function or block is called a global variable. Any function can change its value and is available to all the functions in the program.
Example:
#include<stdio.h>
int x=100;//global variable
int main(){
int a=20;
}
Contributed By: Soham Malakar
Automatic Variable:
An automatic variable is declared using the auto keyword. All the variables in C that are declared inside a block are automatic by default.
Example:
#include<stdio.h>
int main(){
int a=20;//also automatic variable
auto int b=30;//automatic variable
}
Contributed By: Soham Malakar
Static Variable:
A static variable is a variable that is declared using the static keyword. The values of the static variables cannot be changed once initialised and retain the same value in different function calls.
Example:
#include<stdio.h>
int main(){
int a=20;
static int b=90;
}
Contributed By: Soham Malakar
External Variable:
An external variable is a variable which is declared using an external keyword. External variables can be shared to multiple c source files.
Example:
#include<stdio.h>
extern int z=33;
int main(){
int a=20;
}
Contributed By: Soham Malakar
Hence we end the discussion on variables in C.
Please write comments or WhatsApp if you find anything incorrect, or you want to share more information about the topic discussed above.