Quick Links
Variables in C : As we saw earlier, an entity that may vary during program execution is called a variable. Variable names are the names given to locations in memory. These locations can contain integer, real or character constants or a digit. In any language, the types of variable that it can support depend on the types of constants that it can handle. This is because a particular type of variable can hold only the same type of constant.
For example : an integer variable can hold only an integer constant a real variable can hold only a real constant and a character variable can hold only a character constant.
Upper and lowercase letters are distinct because C is case-sensitive.
Example:
int a;
float b;
char c;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
int a=10,b=20;//declaring 2 variable of integer type
float f=20.8;
char c='A';
Rules for defining Variables in C
- A variable name is any combination of 1 to 31 alphabets, digits or underscores.Do not create unnecessarily long variable names as it adds to your typing effort.
- The first character in the variable name must be an alphabet or underscores
- No commas or blanks are allowed within a variable name.
- No special symbol other than an underscore (as in gross_sal) can be used in a variable name.
Valid variable names:
int a;
int _ab;
Invalid variable names:
int 2;
int long;
Types of Variables in C
There are many types of variables in c:
- local variable
- global variable
- static variable
- automatic variable
- external variable
Local Variable
A variable that is declared inside the function or block is called a local variable.
Example:
void function1(){
int x=10;//local variable
}
Global Variable
A variable that is declared outside the function or block is called a global variable. Any function can change the value of the global variable. It is available to all the functions.
Example:
int value=20;//global variable
void function1(){
int x=10;//local variable
}
Static Variable
A variable that is declared with the static keyword is called static variable.
Example:
void function1(){
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default. We can explicitly declare an automatic variable using auto keyword.
Example:
void main(){
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}
External Variables in C
We can share a variable in multiple C source files by using an external variable. To declare an external variable, you need to use extern keyword.
myfile.h
Example:
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);
}
Recommended Posts