Variables In C
Variables are names given to memory locations of computer where data are stored. Locations of variables can contain integer, real or character data types.
How To Declare Variable?
type variable_name;
Variable can not be used, if it is not declared. Data types of variable is needed to be put before the identifier in c language.
Rules for defining variables
- Variables can have alphabets, digits, and underscore.
- Variables can start with the alphabet, and underscore only. It can’t start with a digit.
- No whitespace is allowed within the variable name.
- Variables must not be any reserved word or keyword, e.g. int, float, etc.
Types of Variables in C
- local variable
- global variable
- static variable
- automatic variable
- external variable
Local Variable – It is used & declared inside the function/block.
#include <stdio.h>
void func() {
int a = 5; // local variable
}
int main()
{
func();
}
Global Variable – It is used & declared outside the function/block.
#include <stdio.h>
int a = 5; // global variable
void func() {
printf("%d",a);
}
int main()
{
func();
}
Static Variable – It is a variable that retains its value between multiple function calls. Its value get updated each time after operation on it.
#include <stdio.h>
void func(){
static int a = 30;//static variable
a = a + 10;
printf("%d",a);
}
int main() {
func();
func();
return 0;
}
Automatic Variable – All variables in C language that are declared inside the block, are automatic variables by default.
You can also explicitly declare automatic variable using ‘auto’ keyword.
#include <stdio.h>
void func()
{
int a=4; //local variable (default automatic)
auto int b=5; //automatic variable
}
int main() {
func();
return 0;
}
External Variable – Variables which can be used in different C files. You can declare external variable using extern keyword.
file.h
extern int a=5;//external variable
prog_name.c
#include "file.h"
#include <stdio.h>
void printValue(){
printf("%d", global_variable);
}